由于Java泛型的实现,你不能有这样的代码:

public class GenSet<E> {
    private E a[];

    public GenSet() {
        a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation
    }
}

如何在保持类型安全的同时实现这一点?

我在Java论坛上看到一个解决方案是这样的:

import java.lang.reflect.Array;

class Stack<T> {
    public Stack(Class<T> clazz, int capacity) {
        array = (T[])Array.newInstance(clazz, capacity);
    }

    private final T[] array;
}

但我真的不明白这是怎么回事。


当前回答

传递一个值列表…

public <T> T[] array(T... values) {
    return values;
}

其他回答

根据vnportnoy的语法

GenSet<Integer> intSet[] = new GenSet[3];

创建一个空引用数组,填充为

for (int i = 0; i < 3; i++)
{
   intSet[i] = new GenSet<Integer>();
}

这是类型安全的。

其他人建议的强制选角对我来说并不管用,这是非法选角的一个例外。

然而,这种隐式强制转换工作得很好:

Item<K>[] array = new Item[SIZE];

其中Item是我定义的包含成员的类:

private K value;

通过这种方式,您可以获得一个K类型的数组(如果项只有值)或任何您想在类item中定义的泛型类型。

您不需要将Class参数传递给构造函数。 试试这个。

public class GenSet<T> {

    private final T[] array;

    @SafeVarargs
    public GenSet(int capacity, T... dummy) {
        if (dummy.length > 0)
            throw new IllegalArgumentException(
              "Do not provide values for dummy argument.");
        this.array = Arrays.copyOf(dummy, capacity);
    }

    @Override
    public String toString() {
        return "GenSet of " + array.getClass().getComponentType().getName()
            + "[" + array.length + "]";
    }
}

and

GenSet<Integer> intSet = new GenSet<>(3);
System.out.println(intSet);
System.out.println(new GenSet<String>(2));

结果:

GenSet of java.lang.Integer[3]
GenSet of java.lang.String[2]

一个简单的解决方法是在主类中嵌套第二个“holder”类,并使用它来保存数据。

public class Whatever<Thing>{
    private class Holder<OtherThing>{
        OtherThing thing;
    }
    public Holder<Thing>[] arrayOfHolders = new Holder<Thing>[10]
}

这在Effective Java第二版第5章(泛型)第25项中有介绍…更喜欢列表而不是数组

你的代码将会工作,尽管它会生成一个未检查的警告(你可以用下面的注释来抑制它):

@SuppressWarnings({"unchecked"})

然而,使用List而不是Array可能会更好。

在OpenJDK项目网站上有一个关于这个bug/特性的有趣讨论。