0

What is the concept behind the Generic extend that why is it not allowed to modify the list; why does it throw a compile time error when I add a string to list , since String extends Object and should be legal.

If this gives compilation error , then what is the use of that list that is created then.

         List<? extends Object>  ls=new ArrayList<String>();
         ls.add("asd");  // compilation error

And it compiles in the case of super.

         List<? super Integer> ls1=new ArrayList<Object>();
         ls1.add(1);

I have read Kathy Sierra and Javadoc, but am not able to understand what this means. Please give me a detailed explanation with examples to understand this.

Seeta Somagani
  • 776
  • 1
  • 11
  • 31
anshulkatta
  • 2,044
  • 22
  • 30

2 Answers2

2

You can't add Strings to a List<? extends Object> because ? could be anything.

If you want to put things into a list, its type parameter should be a superclass of the type you want to put in. (This includes the type itself.)

If you want to get things from a list, its type parameter should be a subclass of the type you want to take out. (This includes the type itself.)

This can be remembered with the acronym PECS - producer-extends, consumer-super.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • so this kind of list can only be used in arguments , not to instantiate so that we can add objects into it , right ?? – anshulkatta Jun 05 '13 at 14:05
  • ? cant be anything , i typed it safe as – anshulkatta Jun 05 '13 at 14:06
  • You can create and initialize a reference a List extends Object>, as you have above. You can use it as an argument or elsewhere. You can't add an item through this reference, because the parameterized type *of the reference's type* could be Object or any subclass. You've assigned a List to the reference, but typechecking is checking the type of the reference, not the type of the object to which it points at runtime. – Andy Thomas Jun 05 '13 at 14:13
0

Compiler does not care try to analize what actual generic type of list is, it checks only ls declared generic type. It is the same as here

void add(List<? extends Object> ls) {
   ls.add("1");
   ...

ls can be eg a list of Integers, you cannot add "1" to it.

Similar explanation applies to super

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275