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);
one question about Generics
Moderator: admin
-
- Posts: 53
- Joined: Thu Nov 22, 2012 12:01 am
- Contact:
-
- Site Admin
- Posts: 10388
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: one question about Generics
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.
I suggest you read about this from a book because this is a very important concept.
-
- Posts: 53
- Joined: Thu Nov 22, 2012 12:01 am
- Contact:
Re: one question about Generics
thank u
Who is online
Users browsing this forum: Google [Bot] and 4 guests