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

标签 java

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/

相关文章:

java - Spring转换器不转换自定义实体

java - Swing drop 回调期间是否禁止更改组件层次结构?

java - 通过套接字发送压缩数据

java - System.out 字符编码

java - 如何在JSF页面中显示ArrayList

java - 我在使用 JavaFX 画十字时遇到问题

java - Jibx Maven 插件 : how to set Java package in xsd -> Java transform when namespace was defined

java - 如何从我的 Android 应用程序中的另一个 Activity 访问主 webview 实例?

java - 如何在 Eclipse 中向 Java 文件添加自定义警告?

java - 应用小程序的安全策略