• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

why l.add() method is not working in this context?

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class p1
{
public static void main(String a[])
{
List<? extends String> l=new ArrayList<String>();
l.add("abc");

}
};
 
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"sandeep",
Welcome to the ranch. You may not be aware of the ranch Naming Policy. Please read it carefully and change your name accordingly (you need to set both first and last names). Thank you.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The parameter of add() is <? extends String> which means an unknown subtype of String is in there. String is not a great example. You should look at a simplier example like this :

So, l is a List<? extends A>. But what can you really put in there ? In the doSomething method, you don't know what kind of list it really is. Could you call l.add(new C()) ? C extends A. But we declared the list as containing B objects. With this type of wildcards, you can get objects from a collection, but not add any.
 
passwords must contain 14 characters, a number, punctuation, a small bird, a bit of cheese and a tiny ad.
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic