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

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

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

原因是什么?


当前回答

我喜欢间接给出的答案 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中创建泛型数组类型。我误解了这个问题吗?

其他回答

试试这个:

List<?>[] arrayOfLists = new List<?>[4];

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

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

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

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

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

丑陋,但Java是快乐的。

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

我喜欢间接给出的答案 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中创建泛型数组类型。我误解了这个问题吗?

T vals [];/ /好吧

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

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