为什么 ArrayList 实现使用 Object[]? [英] Why does the ArrayList implementation use Object[]?
问题描述
Java ArrayList
基于对象数组的实现.
谁能解释一下为什么 ArrayList
的实现使用数组 Object[]
而不是 E[]
来存储数据?使用 Object[]
有什么好处?
In Java ArrayList<E>
implementation base on a array of objects.
Can anybody explain me why implementation of ArrayList<E>
uses array Object[]
for data storage instead of E[]
? What the benefit of using Object[]
?
推荐答案
在 Java 中,创建泛型数组并不简单.
简单的方法不编译:
public class Container<E> {
E[] arr = new E[3]; // ERROR: Cannot create a generic array of E
}
用 Object
替换 E
,一切都很好(代价是容器实现中其他地方的复杂性增加).
Replace E
with Object
, and all is well (at the expense of added complexity elsewhere in the container implementation).
有多种替代方法,但它们提出了一组不同的权衡.如需更多讨论,请参阅如何在 Java 中创建泛型数组?
There are alternative approaches, but they present a different set of tradeoffs. For an extensive discussion, see How to create a generic array in Java?
这篇关于为什么 ArrayList 实现使用 Object[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!