【问题标题】:Array of a generic class [duplicate]泛型类的数组[重复]
【发布时间】:2013-05-05 15:16:59
【问题描述】:

我有一个 Box 类,它包含一个值,我想创建一个此类的数组。

盒子类:

public class Box<T> {
    public T t;
    public Box(T t){ this.t = t; }
}

测试类:

public class Test {
    public static void main(String[] args) {
        Box<Integer>[] arr = new Box<Integer>[10];
    }
}

编译器说:

无法创建 Box 的通用数组

我想知道为什么我们不能这样做,我该怎么做?

【问题讨论】:

标签: java generics


【解决方案1】:

Java 不允许使用泛型数组。

您可以在此处找到更多信息:Java Generics FAQ

为了快速修复,请使用List(或ArrayList)而不是数组。

List<Box<Integer>> arr = new ArrayList<Box<Integer>>();

问题的详细解释: Java theory and practice: Generics gotchas:

【讨论】:

    【解决方案2】:

    这曾经有效(产生警告),仍然应该做你需要的:

     Box<Integer> arr = (Box<Integer>[]) new Box[10];
    

    【讨论】:

      【解决方案3】:

      不,你不能因为type erasure,有两种可能的解决方法:

      • 使用ArrayList&lt;Box&lt;Integer&gt;&gt;
      • 通过java.lang.reflect.Array.newInstance(clazz, length) 使用反射(但您会收到警告)

      【讨论】:

      • 没有理由使用Array.newInstance。组件类型在编译时是已知的。
      【解决方案4】:
      Box<Integer> arr = (Box<Integer>[])new Box<?>[10];
      

      【讨论】:

        猜你喜欢
        • 2019-06-04
        • 2011-12-24
        • 1970-01-01
        • 2011-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-06
        • 1970-01-01
        相关资源
        最近更新 更多