I was learning Generics in Java and I came close to a very interesting piece of code. I know in Java it is illegal to add list of one type to another.
List<Integer> integerList = new ArrayList<Integer>();
List<String> stringList=integerList;
So in the second line I get a compile time error.
But if I create a generic method inside a class like this,
class GenericClass <E>{
void genericFunction(List<String> stringList) {
stringList.add("foo");
}
// some other code
}
And in the main class call the method with list of Integer I am not getting any error.
public class Main {
public static void main(String args[]) {
GenericClass genericClass=new GenericClass();
List<Integer> integerList= new ArrayList<Integer>();
integerList.add(100);
genericClass.genericFunction(integerList);
System.out.println(integerList.get(0));
System.out.println(integerList.get(1));
}
}
Output
100
foo
Why I am not getting any error?