Consider a generic method program below:
class GenericTest {
int i;
}
public class GenericMethod {
public <T> List<T> addList(T t, T t1) {
List<T> list=new ArrayList<T>();
list.add(t);
list.add(t1);
return list;
}
public <T> List<T> addList(T t, T t1, List<T> l) {
List<T> list=new ArrayList<T>();
list.add(t);
list.add(t1);
list.addAll(l);
return list;
}
public static void main(String[] args) {
GenericMethod gm=new GenericMethod();
List l=gm.addList(new Integer(42), "java"); //Line 21
System.out.println(l);
List<Object> list = new ArrayList<Object>();
list.add(false);
List l2 = gm.addList("java", new Integer(42), list); //Line 25
System.out.println(l2);
GenericTest gt = new GenericTest();
List l3 = gm.addList("java", gt); //Line 28
System.out.println(l3);
List l4 = gm.addList(gm, gt); //Line 30
System.out.println(l4);
List lst = new ArrayList();
lst.add(new Object());
List l5 = gm.addList("java", new Integer(42), lst); //Line 34
System.out.println(l5);
System.out.println(l5.get(0));
}
}
By going through the Reference link Java Generics - Confusing behavior I am infering that,
In Line 21 since the method is called with both String and Integer, it calls the method with Object for T. Same goes for Line 25 as List has also type Object, it calls the method with Object for T. Calling List with other type will produce an error. Is my inference correct?
What I cannot thought is about
1) Line 28 when String and class is passed,
2) Line 30 when two different class is passed,
3) Line 34 when List declared without type is passed as argument.
Can anyone share their knowledge to clear my understanding. Any help would be appreciated! Thanks!