1

The upper bound wildcard in the method below means we can pass in a list that contains elements of type Object or any List containing elements of type which is subclass Object, I am not understanding why the following is not compiling, because string is subclass of Object:

public static void addSound(List<? extends Object> list) {
list.add("quack"); //does not compile
}
san
  • 263
  • 2
  • 7
  • 14
  • 1
    `List extends Object>` means list of something not defined yet, but that thing is a subtype of `Object`. It does not mean it's a list accepting subclasses `Object` (that would be `List`). In other words, when `? extends Object` is determined, it might be something (still, a subtype of `Object`) that is not `String`. That's why the compiler does not allow you to force a String into `list`. – ernest_k Oct 09 '20 at 07:53
  • 2
    Does this answer your question? [What is PECS (Producer Extends Consumer Super)?](https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super) – Amongalen Oct 09 '20 at 07:54
  • @ernest_k write that as an answer so it can be accepted. – Jeppz Oct 09 '20 at 07:56

1 Answers1

1

Upper bounded generics are immutable. The extended type can be anything that extends object, it could be a list of Ducks. and then you see why it can't work. (list.add(new Duck()) is not the same as "quack")

Lower bound work though

   public static void addSound(List<? super String> list) {
    list.add("quack"); //does compile
   }
Niclas Lindgren
  • 542
  • 6
  • 23
  • I believe your answer also appears here: [Why can't add element in a upper bound generics List?](https://stackoverflow.com/questions/21383139/why-cant-add-element-in-a-upper-bound-generics-list) – Abra Oct 09 '20 at 08:07