Java – why collection ToArray (t []) does not use E []

The toArray method (selected in java.util.arraylist) is as follows:

class ArrayList<E> ....{
    public <T> T[] toArray(T[] a){
        if(a.length < size)
            return (T[]) Arrays.copyof(elementData,size,a.getClass());
        System.arraycopy(elementData,a,size);
        if(a.length > size)
            a[size] = null;
        return a;
    }    
}

I wonder if we can use < E > instead of < T > in this case? like

public E[] toArray(E[] a){
      if(a.length < size)
             return (E[]) Arrays.copyof(elementData,a.getClass());
      System.arraycopy(elementData,size);
      if(a.length > size)
            a[size] = null;
      return a;
}

Since the ArrayList class itself is already generic to < E >, we can use it instead of the new generic type < T >?

Solution

< T > if the required array is base class E. for example, if e is HashMap, but the required array is map [] This is not possible if toArray is locked to E

Because of type erasure, something of this type is not required in a common collection / type But there is no type erasure and array, so the type of array can be very important

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>