Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Doubt in Generics

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic