• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Generics in Java

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Need a help on this topic.

Suppose i have to declare List using Generics how i will declare is -

List<Object> myList = new ArrayList<Object>();

Why it can't be like this?

List<Object> myList = new ArrayList<Emp>();
OR
List<Emp> myList = new ArrayList<Object>();

Emp is my defined class.

Thanks in advance.
 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Why it can't be like this?

List<Object> myList = new ArrayList<Emp>();


Basically because parameterized types are not covariant. A List<Emp> is not a List<Object>.
Check out:
http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ102
for a more complete explanation.
[ April 28, 2007: Message edited by: Garrett Rowe ]
 
Marshal
Posts: 74376
334
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Another explanation, about why a Cage<Animal> is different from a Cage<Lion> and a Cage<Butterfly>, even though Lion and Butterfly are both kinds of Animal, appears in the Java Tutorial.
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic