Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in generics

 
Paras Jain
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am not able to understand why I am not able to add instance of Top class to an arrayslist declared as List <? super Middle>

Please see the following code




Thanks
Paras
 
Naveen Zed
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a type safe Middle collection you cannot add a Top.Thats all.
 
Paras Jain
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But I have declard the Collection type as
List <? super Middle>

not

List <Middle>
 
Alina Petra
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you have a collection declared as List<? super X> where X is a certain class, you are allowed to add to the collection only objects that pass IS-A X relationship.
 
Jae Stryker
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is as the other guys said - You've declared an ArrayList of Middles and are trying to add a object type of Top to it, which does fit the IS-A structure i.e. Top is not a Middle - though Middle is a Top so if you were to change your code to



it would compile.
 
prashanth kumar
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jae Stryker:
The problem is as the other guys said - You've declared an ArrayList of Middles and are trying to add a object type of Top to it, which does fit the IS-A structure i.e. Top is not a Middle - though Middle is a Top so if you were to change your code to



it would compile.


This question often causes me confusion.
Here is an extract that i found out in a website.

So even though "? super T" is a lower bound,it depends on final instatntiation of reference
Ex:

List <? super Top> list = new ArrayList <Top> ();

Even though the above code says,List can take any objects of Top anmd Super types,you can only add objects of Top and Subtypes..

Am i right?
Can anyone explain it bit more

Many Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic