Java – wrong data type – Generic

In the following java code:

import java.util.*;

public class TestGenericMethod {

public static <E> void ArrayToArrayList(E[] a,ArrayList<E> lst) {
    for (E e : a) lst.add(e);
}

public static void main(String[] args) {
    ArrayList<Integer> lst = new ArrayList<Integer>();
    Integer[] intArray = {55,66};  // auto@R_711_2419@
    ArrayToArrayList(intArray,lst);

    for (Integer i : lst) System.out.println(i);    
    String[] strArray = {"one","two","three"};

    //ArrayToArrayList(strArray,lst);   // Compilation Error
}
}

Someone can explain how the compiler knows this line:

ArrayToArrayList(strArray,lst);

Throw exception?

If the method accepts generic data, why does it accept an integer array but not a string array?

Solution

This will not compile because arraytoarraylist requires an array and an array list of the same type:

public static <E> void ArrayToArrayList(E[] a,ArrayList<E> lst) {

The example you commented out tries to call it using a string array and an ArrayList of integer

The following compilation:

String[] strArray = {"one","three"};
      ArrayList<String> strLst = new ArrayList<String>();
      ArrayToArrayList(strArray,strLst);
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
分享
二维码
< <上一篇
下一篇>>