Java List T[] toArray(T[] a) implementation

后端 未结 7 984
小蘑菇
小蘑菇 2020-12-08 02:15

I was just looking at the method defined in the List interface: T[] toArray(T[] a) , and I have a question. Why is it generic? Because of that fact, m

相关标签:
7条回答
  • 2020-12-08 03:18

    The reason this method is as it is is mostly historic.

    There is a difference between generic classes and array types: whereas the type parameters of generic class are erased at run-time, the type of the elements of arrays is not. So, at run-time, the JVM sees no difference between List<Integer> and List<String>, but it does see a difference between Integer[] and String[]! The reason for this difference is that arrays have always been there, from Java 1.0 onwards, whereas generics where only added (in a backward-compatible way) in Java 1.5.

    The Collections API was added in Java 1.2, before the introduction of generics. At that time the List interface already contained a method

    Object[] toArray(Object[] a);
    

    (see this copy of the 1.2 JavaDoc). This was the only way to create an array with a user-specified runtime type: the parameter a served as a type token, that is, it determined the runtime type of the returned array (note that if A is a subclass of B, A[] is considered a subtype of B[] although List<A> is not a subtype of List<B>).

    When generics were introduced in Java 1.5, many existing methods were made generic, and the toArray method became

    <T> T[] toArray(T[] a);
    

    which, after type erasure, has the same signature as the original non-generic method.

    0 讨论(0)
提交回复
热议问题