由于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;
}

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


当前回答

实际上,更简单的方法是创建一个对象数组,并将其转换为所需的类型,如下例所示:

T[] array = (T[])new Object[SIZE];

其中SIZE是一个常量,T是一个类型标识符

其他回答

试试这个。

private int m = 0;
private int n = 0;
private Element<T>[][] elements = null;

public MatrixData(int m, int n)
{
    this.m = m;
    this.n = n;

    this.elements = new Element[m][n];
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            this.elements[i][j] = new Element<T>();
        }
    }
}

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

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中泛型的一个已知且刻意的弱点:它是使用擦除来实现的,因此“泛型”类不知道它们在运行时是用什么类型参数创建的,因此不能提供类型安全,除非实现了一些显式机制(类型检查)。

这是类型安全的唯一答案

E[] a;

a = newArray(size);

@SafeVarargs
static <E> E[] newArray(int length, E... array)
{
    return Arrays.copyOf(array, length);
}

没有人回答你发布的例子中发生了什么。

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;
}

正如其他人所说,泛型在编译过程中被“擦除”。所以在运行时泛型的实例不知道它的组件类型是什么。这样做的原因是历史原因,Sun希望在不破坏现有接口(包括源接口和二进制接口)的情况下添加泛型。

另一方面,数组在运行时知道它们的组件类型。

这个例子通过调用构造函数(构造函数知道类型)的代码传递一个参数,告诉类所需的类型,从而解决了这个问题。

因此,应用程序将用类似于

Stack<foo> = new Stack<foo>(foo.class,50)

构造函数现在知道(在运行时)组件类型是什么,并可以使用该信息通过反射API构造数组。

Array.newInstance(clazz, capacity);

最后,我们有一个类型强制转换,因为编译器无法知道array #newInstance()返回的数组是正确的类型(即使我们知道)。

这种风格有点难看,但它有时是创建泛型类型的最不坏的解决方案,因为无论出于什么原因(创建数组或创建组件类型的实例等),泛型类型都需要在运行时知道它们的组件类型。

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

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

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

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

private K value;

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