由于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 [] createArray(int desiredSize){
    ArrayList<T> builder = new ArrayList<T>();
    for(int x=0;x<desiredSize;x++){
        builder.add(null);
    }
    return builder.toArray(zeroArray());
}

//zeroArray should, in theory, create a zero-sized array of T
//when it is not given any parameters.

private T [] zeroArray(T... i){
    return i;
}

编辑:也许另一种创建这样一个数组的方法,如果你所需要的大小是已知的和小的,将是简单地提供所需的“null”的数量到zeroArray命令?

虽然这显然不如使用createArray代码通用。

其他回答

Java泛型的工作原理是在编译时检查类型并插入适当的类型转换,但在编译后的文件中删除类型。这使得不理解泛型的代码(这是一个深思熟虑的设计决策)可以使用泛型库,但这意味着您通常无法在运行时找到类型。

公共Stack(Class<T> clazz,int capacity)构造函数要求您在运行时传递Class对象,这意味着类信息在运行时可用于需要它的代码。而Class<T>形式意味着编译器会检查你传递的Class对象是否恰好是类型T的Class对象,不是T的子类,也不是T的超类,而是恰好是T。

这意味着您可以在构造函数中创建适当类型的数组对象,这意味着您存储在集合中的对象的类型将在它们被添加到集合时检查它们的类型。

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

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

在Java 8中,我们可以使用lambda或方法引用创建一种泛型数组。这类似于反射方法(传递一个类),但这里我们没有使用反射。

@FunctionalInterface
interface ArraySupplier<E> {
    E[] get(int length);
}

class GenericSet<E> {
    private final ArraySupplier<E> supplier;
    private E[] array;

    GenericSet(ArraySupplier<E> supplier) {
        this.supplier = supplier;
        this.array    = supplier.get(10);
    }

    public static void main(String[] args) {
        GenericSet<String> ofString =
            new GenericSet<>(String[]::new);
        GenericSet<Double> ofDouble =
            new GenericSet<>(Double[]::new);
    }
}

例如,<A> A[] Stream.toArray(IntFunction<A[]>)使用此方法。

这也可以在java 8之前使用匿名类来完成,但是比较麻烦。

根据vnportnoy的语法

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

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

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

这是类型安全的。

我必须反过来问一个问题:你的发电机组是“检查”还是“未检查”? 这是什么意思?

Checked: strong typing. GenSet knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a Class<E> argument, and methods will throw an exception when they are passed arguments that are not of type E. See Collections.checkedCollection. -> in that case, you should write: public class GenSet<E> { private E[] a; public GenSet(Class<E> c, int s) { // Use Array native method to create array // of a type only known at run time @SuppressWarnings("unchecked") final E[] a = (E[]) Array.newInstance(c, s); this.a = a; } E get(int i) { return a[i]; } } Unchecked: weak typing. No type checking is actually done on any of the objects passed as argument. -> in that case, you should write public class GenSet<E> { private Object[] a; public GenSet(int s) { a = new Object[s]; } E get(int i) { @SuppressWarnings("unchecked") final E e = (E) a[i]; return e; } } Note that the component type of the array should be the erasure of the type parameter: public class GenSet<E extends Foo> { // E has an upper bound of Foo private Foo[] a; // E erases to Foo, so use Foo[] public GenSet(int s) { a = new Foo[s]; } ... }

所有这些都是由于Java中泛型的一个已知且刻意的弱点:它是使用擦除来实现的,因此“泛型”类不知道它们在运行时是用什么类型参数创建的,因此不能提供类型安全,除非实现了一些显式机制(类型检查)。