问题描述
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;
}
}
我想知道在这种情况下我们可以使用 而不是
吗?喜欢
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 类本身已经是 <E>
的泛型,那么我们可以使用它来代替新的泛型类型 <T>
吗?
Since the ArrayList class iteself is already generic to <E>
, so could we use that instead of a new generic type <T>
?
推荐答案
<T>
的重点是如果想要的数组是 E
.例如,如果 E
是 HashMap
但所需的数组是 Map[]
.如果 toArray
被锁定到 E
这将是不可能的.
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[] 代替的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!