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;
}
Since the ArrayList class iteself is already generic to <E>, so could we use that instead of a new generic type <T> ?
The point of the
<T>is if the array desired is of a base class ofE. For example ifEisHashMapbut the desired array wasMap[]. IftoArraywere locked down toEthis 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.