• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Generics

 
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks,Ankit.
 
Men call me Jim. Women look past me to this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic