gpt4 book ai didi

Java - ArrayList 不为其实例字段 "elementData "使用正式类型参数

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:46:05 24 4
gpt4 key购买 nike

ArrayList 选择在其实例变量elementData 中只使用Object 的引用类型。

使用 Object 作为其引用类型需要显式转换才能获得其元素的正确实例类型。如果它只是在声明所述实例字段时使用类型参数有什么区别?

这样,我认为它可以消除抑制未经检查的显式转换的需要。

// From Java API:
public E get(int index) {
rangeCheck(index);

return elementData(index);
}

@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}

可以这样吗?

private transient E[] elementData;

public E get(int index) {
rangeCheck(index);

return elementData[index];
}

请分享您的想法。干杯!

最佳答案

我已经得到了答案,它来自阅读 Joshua Bloch 的“Effective Java 2nd Edition”。它在第 26 项中说..

Which of the two techniques you choose for dealing with the generic array creation error is largely a matter of taste. All other things being equal, it is riskier to suppress an unchecked cast to an array type than to a scalar type, which would suggest the second solution. But in a more realistic generic class than Stack, you would probably be reading from the array at many points in the code, so choosing the second solution would require many casts to E rather than a single cast to E[], which is why the first solution is usedmore commonly [Naftalin07, 6.7]

ArrayList 使用第二种技术来处理通用数组创建,即禁止转换为标量类型。

关于Java - ArrayList 不为其实例字段 "elementData "使用正式类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25929692/

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