Java不允许我们这么做的原因是什么
private T[] elements = new T[initialCapacity];
我可以理解。net不允许我们这样做,因为在。net中,值类型在运行时可以有不同的大小,但在Java中,所有类型的T都将是对象引用,因此具有相同的大小(如果我错了请纠正我)。
原因是什么?
Java不允许我们这么做的原因是什么
private T[] elements = new T[initialCapacity];
我可以理解。net不允许我们这样做,因为在。net中,值类型在运行时可以有不同的大小,但在Java中,所有类型的T都将是对象引用,因此具有相同的大小(如果我错了请纠正我)。
原因是什么?
当前回答
主要原因是Java中的数组是协变的。
这里有一个很好的概述。
其他回答
试试这个:
List<?>[] arrayOfLists = new List<?>[4];
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不会被抛出。
正如其他人已经提到的,你当然可以通过一些技巧来创造。
但不建议这样做。
因为类型擦除,更重要的是数组中的协方差,它允许子类型数组被赋给超类型数组,这迫使你在试图取回值时使用显式类型强制转换,导致运行时ClassCastException,这是泛型试图消除的主要目标之一:在编译时进行更强的类型检查。
Object[] stringArray = { "hi", "me" };
stringArray[1] = 1;
String aString = (String) stringArray[1]; // boom! the TypeCastException
一个更直接的例子可以在Effective Java: Item 25中找到。
协方差:如果S是T的子类型,则类型S[]的数组是T[]的子类型
主要原因是Java中的数组是协变的。
这里有一个很好的概述。
答案已经给出了,但如果你已经有一个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