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

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

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

原因是什么?


当前回答

这是因为Java的数组(与泛型不同)在运行时包含关于其组件类型的信息。因此,在创建数组时必须知道组件类型。因为您不知道T在运行时是什么,所以您不能创建数组。

其他回答

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

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

引用:

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

Oracle教程:

You cannot create arrays of parameterized types. For example, the following code does not compile: List<Integer>[] arrayOfLists = new List<Integer>[2]; // compile-time error The following code illustrates what happens when different types are inserted into an array: Object[] strings = new String[2]; strings[0] = "hi"; // OK strings[1] = 100; // An ArrayStoreException is thrown. If you try the same thing with a generic list, there would be a problem: Object[] stringLists = new List<String>[]; // compiler error, but pretend it's allowed stringLists[0] = new ArrayList<String>(); // OK stringLists[1] = new ArrayList<Integer>(); // An ArrayStoreException should be thrown, // but the runtime can't detect it. If arrays of parameterized lists were allowed, the previous code would fail to throw the desired ArrayStoreException.

对我来说,这听起来很软弱。我认为任何对泛型有充分理解的人,都完全可以理解,甚至期望,在这种情况下ArrayStoredException不会被抛出。

主要原因是Java中的数组是协变的。

这里有一个很好的概述。

这是因为Java的数组(与泛型不同)在运行时包含关于其组件类型的信息。因此,在创建数组时必须知道组件类型。因为您不知道T在运行时是什么,所以您不能创建数组。