coder
coder

Reputation: 337

Wrong data type - Generics

In the below 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};  // autobox
    ArrayToArrayList(intArray, lst);

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

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

Can someone explain me how does the compiler know that this line:

ArrayToArrayList(strArray, lst);

throws an exception ?

If the method accepts a generic type of data why does it accept an Integer array but not a String array ?

Upvotes: 3

Views: 109

Answers (2)

NPE
NPE

Reputation: 500713

This doesn't compile because ArrayToArrayList expects an array and an array list of the same type (E):

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

Your commented-out example tries to call it with an array of String and an ArrayList of Integer.

The following does compile:

      String[] strArray = {"one", "two", "three"};
      ArrayList<String> strLst = new ArrayList<String>();
      ArrayToArrayList(strArray, strLst);

Upvotes: 5

Rohit Jain
Rohit Jain

Reputation: 213331

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

In this method, the type of the ArrayList passed should be of same type as the type of your array (E)

So, if you are passing ArrayList<Integer>, you have to pass an Integer[], as you have used same type E for both of them.

Now in this invocation: -

ArrayToArrayList(strArray, lst);

your lst is of type ArrayList<Integer>, and your strArray is String[], so there is a type mismatch.

Upvotes: 2

Related Questions