-1

Could anyone please let me know why this doesn't work?

List<? super Person> list = new ArrayList<>();
list.add(new Object());

My understanding is that the variable list can hold any value as long as it is a superclass of Person. Object is definitely a superclass of Person, then why it can't be added to the list?

Prabhjot
  • 4,496
  • 2
  • 18
  • 22

1 Answers1

0

Suppose you have a class hierarchy as Object -> Movable -> Person and in that case List<? super Person> can point to:

  1. list of Movable ( List<Movable>) or
  2. list of Object (List<Object>)

You do not know what type of elements (Movable or Object) list will have exactly at run time (generics is compile time phenomenon).

That is the reason insertion is not allowed in such case because it might end up adding Object to list of Movable at runtime. So golden rule is Producer Extends Consumer Super.

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95