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

Doubt in Generics

 
TC Rangarajan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic