2

I am reseaerching a case and I want to know why I can modify a list when using ? extends and when I use ? super I can.

Leet see this dummy code:

class LivingBeing {
}

class Human extends LivingBeing {
}

class Citizen extends Human {
}

Imagine I have this 3 instances:

LivingBeing lb = new LivingBeing();
Human h = new Human();
Citizen c = new Citizen();

Well, I can declare and modify the list with no problem if I code:

List<? super Human> l = new ArrayList<LivingBeing>();
l.add(h);

But WHY I am getting compiler error If I do something like:

//COMPILE ERROR
List<? extends Human> l = new ArrayList<Human>();
l.add(h);  

I have very clear what ? extends Class and ? extends Class means, I just I don't understand whey I can't modify a list using extends and I can do it with ? super.

Also, I know that I get a compile error if I try to modify some list declared just with the wildcard:

List<?> list = new ArrayList<>();
Daniel Hernández
  • 4,078
  • 6
  • 27
  • 38
  • 3
    [This answer in particular](http://stackoverflow.com/a/21351277/1079354) from that dupe is likely the best thing you can use to understand what's going on. – Makoto Sep 14 '15 at 20:17
  • Thanks ! I didn't even know that the principle PECS exists, so I wasn't able to do some good search at stackoverlfow :) thanks – Daniel Hernández Sep 14 '15 at 20:23

0 Answers0