为什么这段代码可以编译:
ArrayList strings = new ArrayList();
strings.add("s1");
strings.add("s2");
ArrayList<Integer> numbers = new ArrayList<Integer>(strings);
考虑到相关构造函数需要 Collection<? extends E>
哪里E
在这种情况下是整数?原始类型中如何包含对象 ArrayList
E
的子类?或者是否有一些隐藏的编译器魔法可以允许此用于遗留目的?
最佳答案
检查ArrayList
构造函数:
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
elementData
是对象数组:
transient Object[] elementData;
很新ArrayList(Collection<? extends E> c)
将接受所有Collection
,不在乎E
类型
它会抛出 ClassCastExceptionwhen
当我们使用它时:
Integer i= numbers.get(1);
关于java - 为什么 ArrayList<E> 构造函数允许原始 ArrayList 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40650944/