Java List toArray(T[] a) implementation

后端 未结 5 1333
挽巷
挽巷 2021-01-04 13:26

I was just looking at the method defined in the List interface:

Returns an array containing all of the elements in this list in the correct order; the

5条回答
  •  时光说笑
    2021-01-04 13:36

      357       public  T[] toArray(T[] a) {
      358           if (a.length < size)
      359               // Make a new array of a's runtime type, but my contents:
      360               return (T[]) Arrays.copyOf(elementData, size, a.getClass());
      361           System.arraycopy(elementData, 0, a, 0, size);
      362           if (a.length > size)
      363               a[size] = null;
      364           return a;
      365       }
    

    Maybe so it has a runtime type?

    From wiki:

    Consequently, instantiating a Java class of a parameterized type is impossible because instantiation requires a call to a constructor, which is unavailable if the type is unknown.

提交回复
热议问题