gpt4 book ai didi

java - 为什么 ArrayList 构造函数允许原始 ArrayList 参数

转载 作者:行者123 更新时间:2023-11-30 07:58:14 27 4
gpt4 key购买 nike

为什么这段代码可以编译:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com