Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics

 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9527
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks,Ankit.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic