wood burning stoves 2.0*
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics" Watch "Generics" New topic
Author

Generics

Abhi vijay
Ranch Hand

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

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

Results in compiler error?
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9291
    
  17

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
Thanks,Ankit.
 
 
subject: Generics
 
Similar Threads
how to add an array to an ArrayList
***Confusing Generic question ****
Generics Doubt
S&B 1.5, Chapter 7, Question 2, answer C
Generics