-2

why does it work? I understood taht "? super Father" only allows Father and GrandFather

enter image description here

Code here-------------------

public class RxTest {

public static void main(String[] args) {


    // extends -> read only
    // super -> write only

    List<? super Father> list = new ArrayList<>();

    list.add(new Child());
    list.add(new Child());

    System.out.println(list.size()); // 2

    // why does it work? I understood taht "? super Father" only allows Father and GrandFather


}

}

class GrandFather { }

class Father extends GrandFather { }

class Child extends Father { }

1 Answers1

1

Don't read "? super Father" as "everything is a supertype of Father".

Read it as "the expected type of elements in this list is a supertype of Father". This may seem like I'm saying the same thing, but it is not the same.

It is saying that the thing which created the actual list (not the wildcarded reference) expects everything in the list to be of a particular type, and that type is a supertype of Father. You can't create a new ArrayList<? super/extends Something>, it has to be a new ArrayList<Something>.

As such, you can add instances of Father (which includes subtypes, like Child), without violating the expectations on the elements in the list.

Remember PECS:

Producer extends, Consumer super

List<? super Father> is a consumer of instances of Father.

This is not the same as "super -> write only" as in your code. You can still read from lower-bounded lists, you just have to treat everything as Object.

Similarly, extends does not mean "read only": you can add existing elements from the list to itself, as well as adding literal null.

Andy Turner
  • 122,430
  • 10
  • 138
  • 216
  • "Similarly, extends does not mean "read only": you can add existing elements from the list to itself" Only if you capture the wildcard into a type variable. It won't work with just a wildcard. – newacct Sep 10 '18 at 17:26
  • @newacct yes, but you can pass a wildcarded list into a method which captures the type variable, so the list being wildcarded in a method is no protection against writing to itself. – Andy Turner Sep 10 '18 at 17:33