为什么ArrayList的实现使用对象[]? [英] Why does the ArrayList implementation use Object[]?
问题描述
在Java的的ArrayList< E>
对象的数组实施基地。
结果任何人都可以解释我为什么实施的ArrayList&LT的; E>
使用数组的对象[]
用于数据存储,而不是 E []
?用什么的好处对象[]
?
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
}
替换电子
与对象
,一切都很好(在增加了复杂性为代价的其他地方容器实现)。
Replace E
with Object
, and all is well (at the expense of added complexity elsewhere in the container implementation).
有替代办法,但他们present一组不同的权衡。对于广泛的讨论,请参阅的Java如何:通用阵列创建
There are alternative approaches, but they present a different set of tradeoffs. For an extensive discussion, see Java how to: Generic Array creation
这篇关于为什么ArrayList的实现使用对象[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!