This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics" Watch "Generics" New topic


Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
List i=new ArrayList<Integer>();
List<Number> l=i;// compiles fine.

List<Number> l=new ArrayList<Integer>();

Results in compiler error?
Ankit Garg

Joined: Aug 03, 2008
Posts: 9434

Abhi when you use this code

List i=new ArrayList<Integer>();
List<Number> l=i;

It will give you a compile time warning. That your code is not type safe. This is because this code uses legacy style Collections. But the second code completely uses generics. So it is supposed to be type safe i.e. nothing wrong can be inserted in your collection so that you don't get a ClassCastException or other unexpected results. So when you write

List<Number> l=new ArrayList<Integer>();

It is now the responsibility of the compiler that it maintains the integrity of the list l. Since the actual object to which l points is supposed to hold only Integers, so it wont allow you to assign it to List<Number> which can hold any of the sub classes of Number which can be of a different type than Integer like Long, Float etc. So the compiler doesn't lets you to run this code...
[ November 26, 2008: Message edited by: Ankit Garg ]

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
I agree. Here's the link:
subject: Generics
It's not a secret anymore!