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

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

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

原因是什么?


当前回答

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

这里有一个很好的概述。

其他回答

这是因为泛型是在他们创建后才添加到java的,所以它有点笨拙,因为java的原始创造者认为在创建数组时,类型应该在创建时指定。这对泛型不起作用,所以你必须这么做 E[] array=(E[]) new Object[15]; 这将编译,但会给出警告。

答案已经给出了,但如果你已经有一个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

类可以声明类型为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; }
}

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

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

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

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

丑陋,但Java是快乐的。

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

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不会被抛出。