Java不允许我们这么做的原因是什么

private T[] elements = new T[initialCapacity];

我可以理解。net不允许我们这样做,因为在。net中,值类型在运行时可以有不同的大小,但在Java中,所有类型的T都将是对象引用,因此具有相同的大小(如果我错了请纠正我)。

原因是什么?


当前回答

引用:

Arrays of generic types are not allowed because they're not sound. The problem is due to the interaction of Java arrays, which are not statically sound but are dynamically checked, with generics, which are statically sound and not dynamically checked. Here is how you could exploit the loophole: class Box<T> { final T x; Box(T x) { this.x = x; } } class Loophole { public static void main(String[] args) { Box<String>[] bsa = new Box<String>[3]; Object[] oa = bsa; oa[0] = new Box<Integer>(3); // error not caught by array store check String s = bsa[0].x; // BOOM! } } We had proposed to resolve this problem using statically safe arrays (aka Variance) bute that was rejected for Tiger. -- gafter

(我相信是尼尔·盖特,但不确定)

在这里查看上下文:http://forums.sun.com/thread.jspa?threadID=457033&forumID=316

其他回答

答案已经给出了,但如果你已经有一个T的实例,那么你可以这样做:

T t; //Assuming you already have this object instantiated or given by parameter.
int length;
T[] ts = (T[]) Array.newInstance(t.getClass(), length);

希望,我能帮忙, Ferdi265

试试这个:

List<?>[] arrayOfLists = new List<?>[4];

在我的例子中,我只是想要一个堆栈数组,就像这样:

Stack<SomeType>[] stacks = new Stack<SomeType>[2];

由于这是不可能的,我使用了以下作为解决方案:

创建一个非泛型包装器类围绕堆栈(例如MyStack) MyStack[] stacks = new MyStack[2]工作得很好

丑陋,但Java是快乐的。

注意:正如BrainSlugs83在问题的评论中提到的,在.NET中完全可以有泛型数组

这是不可能的,因为Java完全在编译器级别上实现了泛型,并且每个类只生成一个类文件。 这叫做类型擦除。

在运行时,已编译的类需要用相同的字节码处理它的所有使用。因此,new T[capacity]将完全不知道需要实例化什么类型。

T vals [];/ /好吧

但是,你不能实例化T的数组 // vals = new T[10];//不能创建T的数组

你不能创建T的数组的原因是没有办法 编译器来了解实际创建的数组类型。