0

My question is why objects with upper-bounded wildcard are immutable while objects with lower-bounded wildcards are not.

to illustrate this i will write some code

List<? super Exception> superException = new ArrayList<>();
superException.add(new Exception());
superException.add(new IOException());
superException.add(new FileNotFoundException());


List<? extends IOException> extendsException = new ArrayList<>();
extendsException.add(new Exception()); // DOES NOT COMPILE
extendsException.add(new IOException()); // DOES NOT COMPILE
extendsException.add(new FileNotFoundException()); // DOES NOT COMPILE

enter image description here

Gaël J
  • 7,665
  • 4
  • 16
  • 29
  • 1
    Relevant question (definitely related, possible duplicate): https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super – JustAnotherDeveloper Oct 03 '21 at 10:10
  • This is about co- and contravariance in subtyping polymorphism. I.e., how can you have sound static types, that is your program type checks and compiles and will never produce a type error at runtime. See: https://dzone.com/articles/covariance-and-contravariance and : https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Arrays – Benjamin Maurer Oct 03 '21 at 10:12
  • 2
    The list is **not** immutable. Try, for example, `extendsException.add(null);`, `extendsException.remove(0);`, or `Collections.swap(extendsException, 0, 1);` – Holger Oct 04 '21 at 11:13

0 Answers0