第一个代码:
List<Integer>[] array = (List<Integer>[]) new Object[size];
它将给出以下异常:
java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.util.List; ([Ljava.lang.Object; and [Ljava.util.List; are in module java.base of loader 'bootstrap')
为什么这是错误的?我只是按照Effective Java Third Edition Page 132 的方法:
第二个代码:
E[] array = (E[]) new Object[size];
但是我发现以下代码有效
第三代码:
List<Integer>[] array = (List<Integer>[]) new List[size];
我的问题:
为什么第一个代码是错误的,但Effective Java中建议使用第二个代码?我有什么误解吗?
例如:为什么下面的代码运行良好,但第一个代码是错误的?
public class Test<E>{
E[] array;
public Test(){
array = (E[]) new Object[10];
}
public E set(E x){
array[0] = x;
System.out.println(array[0]);
return array[0];
}
public static void main(String[] args){
Test<List<Integer>> test = new Test<>();
List<Integer> list = new ArrayList<>();
list.add(1);
test.set(list);
}
}
谁能解释为什么第三个代码是正确的但下面的代码是错误的?
第四个代码:
List<Integer>[] array = new List<Integer>[size];
饮歌长啸
慕莱坞森
MM们
相关分类