Java不允许我们这么做的原因是什么
private T[] elements = new T[initialCapacity];
我可以理解。net不允许我们这样做,因为在。net中,值类型在运行时可以有不同的大小,但在Java中,所有类型的T都将是对象引用,因此具有相同的大小(如果我错了请纠正我)。
原因是什么?
Java不允许我们这么做的原因是什么
private T[] elements = new T[initialCapacity];
我可以理解。net不允许我们这样做,因为在。net中,值类型在运行时可以有不同的大小,但在Java中,所有类型的T都将是对象引用,因此具有相同的大小(如果我错了请纠正我)。
原因是什么?
当前回答
肯定有一个好方法(可能是使用反射),因为在我看来,这正是数组列表。toArray(T[] a)可以。我引用:
public <T> T[] toArray(T[] a) 返回一个数组,其中包含所有 此列表中的元素按正确顺序排列;的运行时类型 返回的数组是指定数组的数组。如果列表符合 指定的数组,则在其中返回。否则,新数组为 的运行时类型分配 这个列表。
因此,一种方法是使用这个函数,即创建一个数组中你想要的对象的数组列表,然后使用toArray(T[] a)来创建实际的数组。不会很快,但你没提你的要求。
有人知道toArray(T[] a)是如何实现的吗?
其他回答
主要原因是Java中的数组是协变的。
这里有一个很好的概述。
正如其他人已经提到的,你当然可以通过一些技巧来创造。
但不建议这样做。
因为类型擦除,更重要的是数组中的协方差,它允许子类型数组被赋给超类型数组,这迫使你在试图取回值时使用显式类型强制转换,导致运行时ClassCastException,这是泛型试图消除的主要目标之一:在编译时进行更强的类型检查。
Object[] stringArray = { "hi", "me" };
stringArray[1] = 1;
String aString = (String) stringArray[1]; // boom! the TypeCastException
一个更直接的例子可以在Effective Java: Item 25中找到。
协方差:如果S是T的子类型,则类型S[]的数组是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[]的数组,但它不能直接实例化这样的数组。相反,一种常见的方法是实例化一个Object[]类型的数组,然后对类型T[]进行窄化转换,如下所示:
public class Portfolio<T> {
T[] data;
public Portfolio(int capacity) {
data = new T[capacity]; // illegal; compiler error
data = (T[]) new Object[capacity]; // legal, but compiler warning
}
public T get(int index) { return data[index]; }
public void set(int index, T element) { data[index] = element; }
}
这是因为Java的数组(与泛型不同)在运行时包含关于其组件类型的信息。因此,在创建数组时必须知道组件类型。因为您不知道T在运行时是什么,所以您不能创建数组。