Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics in Java  RSS feed

 
Vrushali Gore
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • 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.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • 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 ]
 
Campbell Ritchie
Marshal
Posts: 55698
163
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!