wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt 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 "Doubt in Generics" Watch "Doubt in Generics" New topic
Author

Doubt in Generics

TC Rangarajan
Greenhorn

Joined: Apr 15, 2008
Posts: 3
Consider the Code below:

public static void main(String[] ar)throws Error{
List<? super Object> a=new ArrayList<Object>();
add(a,new Object());
}
static <T> List add(List<T> L,T o){
return L;
}


Note the Highlighted Code. this Code compiles fine.if i change the line to
List<? extends Object> a=new ArrayList<Object>();
add(a,new Object());
It shows compliation error. I assume Object extends Object is true.Then why is the Compilation Error coming? Can anyone help me with this.
Hemnathbabu Kottaiveedu
Greenhorn

Joined: Mar 13, 2008
Posts: 28
When you use



the type parameter T in the method is resolved to Object. This is done using the List reference a. Therefore the code compiles fine. You can try replacing Object by say Integer and then try running the code. It gives compiler error.

Now when you replace the super keyword with extends

the type parameter is resolved using the second argument passed in the method and not using List reference a. That comes out to be Object and it generates compiler error saying that List<? extends Object> a cannot be assigned to List<T> where T is Object.

In the first case it accepted Object because I guess super allows the list to be modified whereas extends does not.

This error can be resolved by declaring the method as


SCJP 5 (100%)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in Generics
 
Similar Threads
how can I add some stuff in returned List?
Generic question with ?
generic - ? super...
Generics
Generics Question: