This question already has answers here:
Cannot create an array of LinkedLists in Java…?
(9个答案)
Generic arrays in Java
(5个答案)
Java Error: New Generic TreeNode Array
(2个答案)
6年前关闭。
我有一个Box类,其中保存一个值,并且我想创建一个此类的数组。
箱类:
测试类别:
编译器说:
无法创建Box的通用数组
我想知道为什么我们不能做到这一点,我该怎么做?
问题的详细说明:
Java theory and practice: Generics gotchas:
(9个答案)
Generic arrays in Java
(5个答案)
Java Error: New Generic TreeNode Array
(2个答案)
6年前关闭。
我有一个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不允许通用数组。
您可以在这里找到更多信息:Java Generics FAQ。
要快速修复,请使用List(或ArrayList)代替Array。
List<Box<Integer>> arr = new ArrayList<Box<Integer>>();
问题的详细说明:
Java theory and practice: Generics gotchas: