标签:col war fir 数组使用 swa 泛型 detail 创建 sdn
起因:
今天在看LinkedList源码时,发现
public <T> T[] toArray(T[] a)方法创建一个泛型数组使用了很奇怪的方式
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size)
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
a = (T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
int i = 0;
Object[] result = a;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
if (a.length > size)
a[size] = null;
return a;
}
疑问:为什么不直接使用T[] a = new T[size]来创建泛型数组?
在eclipse测试时,报错

百度上搜索后
总结
java数组时是协变,即Base[] base= new Sub[];Base是Sub的父类
先假设Java可以创建泛型数组,由于java泛型的类型擦除和数组的协变。下面的代码将会编译通过。但是运行时会报错
List<String>[] stringLists=new List<String>[1]; List<Integer> intList = Arrays.asList(40); Object[] objects = stringLists; Objects[0]=intList; String s=stringLists[0].get(0);
java集合不支持协变,因此出现了泛型
标签:col war fir 数组使用 swa 泛型 detail 创建 sdn
原文地址:https://www.cnblogs.com/lt123/p/13269971.html