为什么Collection.toArray(T [])不采取E [],而不是 [英] Why Collection.toArray(T[]) doesn't take an E[] instead
问题描述
的的toArray
办法(让挑的 的java.util.ArrayList
)如下:
The toArray
method (lets pick the implementation in java.util.ArrayList
) is the following:
class ArrayList<E> ....{
public <T> T[] toArray(T[] a){
if(a.length < size)
return (T[]) Arrays.copyof(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if(a.length > size)
a[size] = null;
return a;
}
}
我想知道我们可以使用&LT; E&GT;
而不是&LT的; T&GT;
在这种情况下?像
I am wondering could we use <E>
instead of <T>
in this case ? like
public E[] toArray(E[] a){
if(a.length < size)
return (E[]) Arrays.copyof(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if(a.length > size)
a[size] = null;
return a;
}
由于ArrayList类iteself已经是通用的&LT; E&GT;
,这样我们就可以使用,而不是一个新的通用型&LT; T&GT ;
?
Since the ArrayList class iteself is already generic to <E>
, so could we use that instead of a new generic type <T>
?
推荐答案
的&LT点; T&GT;
是,如果需要的数组是一个基类的电子
。例如,如果电子
是的HashMap
,但所需的阵列是地图[]
。如果的toArray
被锁定到电子
这是不可能的。
The point of the <T>
is if the array desired is of a base class of E
. For example if E
is HashMap
but the desired array was Map[]
. If toArray
were locked down to E
this would not be possible.
不需要在泛型集合/类型,由于类型擦除这种类型的东西。但没有类型擦除使用数组这样的数组类型可以是非常重要的。
This type of thing is not needed in generic collections / types due to type-erasure. But there is no type-erasure with arrays so the type of the array can be very important.
这篇关于为什么Collection.toArray(T [])不采取E [],而不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!