Page 1 of 1

one question about Generics

Posted: Sat Mar 22, 2014 12:36 am
by icepeanuts
I just tried the code below. I thought it should throw an exception at line A because intlist is declared as a list of Integers. But the result surprised me: it works well, printing "10 20 hello". Do you know why?

List<Integer> intList = new ArrayList<>();
intList.add(10);
intList.add(20);
List list = intList;
list.add("hello"); // line A
System.out.println(list);

Re: one question about Generics

Posted: Sat Mar 22, 2014 6:32 am
by admin
This is a very good question and it arises because of a very fundamental aspect of generics. You must understand that generics exist only at compile time. Once you compile the code, all information about generics is removed. The JVM has absolutely no idea about generics. This means List<integer> and List are actually same. That is why once you start using a generic reference as non generic, you can store any thing into it. The compiler will issue a warning though.
I suggest you read about this from a book because this is a very important concept.

Re: one question about Generics

Posted: Sat Mar 22, 2014 5:18 pm
by icepeanuts
thank u