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

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

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

原因是什么?


当前回答

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

其他回答

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

引用:

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 vals [];/ /好吧

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

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

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

我喜欢间接给出的答案 Gafter。然而,我认为这是错误的。我稍微修改了一下加福特的代码。它编译并运行一段时间,然后在Gafter预测的地方爆炸

class Box<T> {

    final T x;

    Box(T x) {
        this.x = x;
    }
}

class Loophole {

    public static <T> T[] array(final T... values) {
        return (values);
    }

    public static void main(String[] args) {

        Box<String> a = new Box("Hello");
        Box<String> b = new Box("World");
        Box<String> c = new Box("!!!!!!!!!!!");
        Box<String>[] bsa = array(a, b, c);
        System.out.println("I created an array of generics.");

        Object[] oa = bsa;
        oa[0] = new Box<Integer>(3);
        System.out.println("error not caught by array store check");

        try {
            String s = bsa[0].x;
        } catch (ClassCastException cause) {
            System.out.println("BOOM!");
            cause.printStackTrace();
        }
    }
}

输出为

I created an array of generics.
error not caught by array store check
BOOM!
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at Loophole.main(Box.java:26)

在我看来,你可以在java中创建泛型数组类型。我误解了这个问题吗?