one question about Generics

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
icepeanuts
Posts: 53
Joined: Thu Nov 22, 2012 12:01 am
Contact:

one question about Generics

Post 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);

admin
Site Admin
Posts: 10388
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: one question about Generics

Post 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.

icepeanuts
Posts: 53
Joined: Thu Nov 22, 2012 12:01 am
Contact:

Re: one question about Generics

Post by icepeanuts »

thank u

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 5 guests