Why is the parameter type of the Java ArrayList. toArray (T []) method T rather than E ?, Arraylisttoarray

Source: Internet
Author: User

Why is the parameter type of the Java ArrayList. toArray (T []) method T rather than E ?, Arraylisttoarray

I made code review for my colleagues two days ago. I felt that I had not mastered Java's Generics well. Then I took out the article titled objective Java 1 and looked at the relevant chapters. In Item 24: Eliminate unchecked warnings, the author takespublic <T> T[] toArray(T[] a)The method is used as an example to illustrate how to use variables.@SuppressWarningsAnnotation.

ArrayList is a generic class, which is declared as follows:

public class ArrayList<E> extends AbstractList<E>    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

This classtoArray(T[] a)The method is a generic method, which is declared and implemented as follows:

 1: @SuppressWarnings("unchecked") 2: public <T> T[] toArray(T[] a) { 3:     if (a.length < size) 4:         // Make a new array of a's runtime type, but my contents: 5:         return (T[]) Arrays.copyOf(elementData, size, a.getClass()); 6:     System.arraycopy(elementData, 0, a, 0, size); 7:     if (a.length > size) 8:         a[size] = null; 9:     return a;10: }

This method is actually declared in the Collection interface. Because we often use ArrayList, here we use ArrayList as an example.

1 Why are declared as different types?

My question is: why does this method use type T instead of the ArrayList type E? That is to say, why is this method not declared as follows:

public E[] toArray(E[] a);

If the types are the same, the parameter type error can be found during compilation. If the type is different, it is easy to generate runtime errors. For example, the following code:

1: // create an ArrayList2: List <String> strList = new ArrayList <String> (); 3: strList. add ("abc"); 4: strList. add ("xyz"); 5: // converts the current strList into a Number array. Note that the following statements have no compilation errors. 6: Number [] numArray = strList. toArray (new Number [0]);

Run the above Code,Line 6Will throwjava.lang.ArrayStoreExceptionException.

If the toArray method uses type E, Statement 2 produces a compilation error. Compilation errors are more friendly than runtime errors. In addition, the main purpose of generics is to eliminate ClassCastException during compilation for type security. This method does the opposite. Is this a big bug? I have encountered a Java bug, but I still don't believe it.

I have been discussing this issue many times, such as 2, 3, and 4.

2. Increased flexibility

This declaration is more flexible, and you can convert the elements in the current list into an array of a more general type. For example, if the current list type is Integer, we can convert its elements into a Number array.

1: List<Integer> intList = new ArrayList<Integer>();2: intList.add(1);3: intList.add(2);4: Number[] numArray = intList.toArray(new Number[0]);

If this method is declared as type E, the above Code will be compiled incorrectly. It seems that this method is better to declare as follows:

public <T super E> T[] toArray(T[] a);

However,<T super E>Such syntax does not exist in Java. And even if it exists, it does not work on arrays. For this reason, even if T is the parent class of E, or T is the same as E, it cannot be completely avoided.java.lang.ArrayStoreExceptionException 5, 6, and 7. See the following two sections of code. In the first code, T is the parent class of E, and in the second code, T is the same as E. Both sections of code throw an exception.

Code 1:

1: List <Integer> intList = new ArrayList <Integer> (); 2: intList. add (1); 3: intList. add (2); 4: 5: Float [] floatArray = new Float [2]; 6: // Float is a subclass of Number, so Float [] is a subclass of Number [] 7: Number [] numArray = floatArray; 8: // The following statement will throw an ArrayStoreException 9: numArray = intList. toArray (numArray );

Code 2:

1: List <Number> intList = new ArrayList <Number> (); 2: // The List type is Number. However, Number is an abstract class and can only store its subclass instance 3: intList. add (new Integer (1); 4: intList. add (new Integer (2); 5: 6: Float [] floatArray = new Float [2]; 7: // Float is a subclass of Number, therefore, Float [] is a subclass of Number [] 8: Number [] numArray = floatArray; 9: // The following statement will throw the ArrayStoreException 10: numArray = intList. toArray (numArray );

The preceding exceptions are caused by this fact: if A is the parent class of B, A [] is the parent class of B. All classes in Java are inherited from objects, and Object [] is the parent class of all arrays.

The example in Article 8 shows that even if the type of this method is declared as E, it cannot be avoided.ArrayStoreExceptionException.

This exception is also mentioned in the document of this method:

ArrayStoreException if the runtime type of the specified array is not a supertype of the runtime type of every element in this list.
3. compatible with versions earlier than Java 1.5

Before Java introduced Generics (Generics was introduced in JDK1.5), this method appeared in 9. At that time, it was declared as follows:

public Object[] toArray(Object[] a)

After the emergence of Generics, many classes and methods become generic. This method is also described as follows:

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

This statement can be compatible with version 10 earlier than Java 1.5.

4. Over two long-winded statements

This method requires an array parameter. If the length of this array is greater than or equal to the size of the current list, the elements in the list will be stored in this array; if the length of this array is smaller than the size of the current list, A new array is created and the elements in the current list are saved to the newly created array. To improve efficiency, if possible, the length of the input array must be greater than or equal to the size of the list to avoid creating an array using this method.

1: List <Integer> intList = new ArrayList <Integer> (); 2: intList. add (1); 3: intList. add (2); 4: // input an array with a length of 0 5: Number [] numArray1 = intList. toArray (new Number [0]); // Statement 16: // input an array with the same length as that of intList. 7: Number [] numArray2 = intList. toArray (new Number [intList. size ()]); // Statement 2

In addition, the array as a parameter cannot benullOtherwise, it will throwNullPointerExceptionException.

Footnotes: 1

Valid Java (2nd Edition)

2

Link

3

Link

4

Link

5

Link

6

Link

7

Link

8

Link

9

Link

10

Link

Created: Wed

Emacs 24.5.1 (Org mode 8.2.10)

Validate

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.