Two Laptop Bag*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem in generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem in generics" Watch "Problem in generics" New topic
Author

Problem in generics

Paras Jain
Ranch Hand

Joined: Feb 26, 2005
Posts: 137
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


Paras Jain
SCJP 5.0
Naveen Zed
Ranch Hand

Joined: Aug 11, 2006
Posts: 61
In a type safe Middle collection you cannot add a Top.Thats all.
Paras Jain
Ranch Hand

Joined: Feb 26, 2005
Posts: 137
But I have declard the Collection type as
List <? super Middle>

not

List <Middle>
Alina Petra
Greenhorn

Joined: Oct 17, 2006
Posts: 26
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

Joined: Oct 31, 2006
Posts: 21
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

Joined: Mar 22, 2004
Posts: 162
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


SCJP1.5(86%)<br />SCWCD1.4(95%)<br />SCBCD1.3(92%)<br />IBM 252
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem in generics