Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Exceptions and Generics

    Wildcards and PECS

    Generics are invariant: List<Integer> is not a List<Number>, even though Integer is a Number:

    Chapter 10 of 104 min readOften asked in interviews

    The Plain Picture#

    A fruit basket that holds only apples. Is it "a basket of fruit"? For taking fruit out — yes, anything you take out is a fruit. For putting fruit in — no! If someone treats it as a general fruit basket and drops in a banana, it's no longer an apple basket.

    The Real Names#

    • Generics are invariant: List<Integer> is not a List<Number>, even though Integer is a Number:

      Java
      List<Integer> ints = new ArrayList<>();
      
      List<Number> nums = ints; // compile error
      Output
      error: incompatible types: List<Integer> cannot be converted to List<Number>

      If it were allowed, you could nums.add(3.14) and a Double would sit inside ints — the banana in the apple basket. (Arrays allowed exactly this, and got the ArrayStoreException in Ch 9.)

    • A wildcard ? means "some type I don't know exactly":

      • List<? extends Number> — a list of some subtype of Number. You can read Numbers out; you can't add (the compiler doesn't know which subtype it really holds).

      • List<? super Integer> — a list of Integer or some supertype. You can add Integers; reading gives you only Object.

      • List<?> — a list of something; read as Object, can't add.

    • PECS — Producer Extends, Consumer Super (from Joshua Bloch's Effective Java):

      • if a parameter produces values your method reads → ? extends T;

      • if it consumes values your method writes → ? super T.

    Under the Hood#

    Java
    static double sum(List<? extends Number> nums) {
        // PRODUCER: we only read from it
        double s = 0;
        for (Number n : nums) s += n.doubleValue();
        return s;
    }
    
    System.out.println(sum(List.of(1, 2, 3)) + " " + sum(List.of(1.5, 2.5))); // 6.0 4.0
    
    // works with List<Integer>, List<Double>, List<Long>... one method for all
    
    static void addScores(List<? super Integer> out) {
        // CONSUMER: we only write Integers into it
        out.add(90);
        out.add(75);
    }
    
    List<Number> sink = new ArrayList<>();
    
    addScores(sink);
    
    List<Object> sink2 = new ArrayList<>();
    
    addScores(sink2);
    
    System.out.println(sink + " " + sink2); // [90, 75] [90, 75]

    The Java library uses exactly this. Collections.copy is declared as:

    Java
    static <T> void copy(List<? super T> dest, List<? extends T> src)
    //                        consumer: super      producer: extends

    and Collections.max as <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) — the ? super T lets a class be compared using a compareTo it inherited from a parent.

    When you don't need wildcards: if a parameter is both read from and written to, use a plain List<T>. Wildcards are mostly for library-style methods that should accept as many types as possible.

    Check yourself

    4 questions
    1

    Why isn't List<Integer> a subtype of List<Number>?

    Show answer

    If it were, you could add a Double through the List<Number> reference into a list that must only hold Integers.

    2

    What can you do with a List<? extends Number>? What can't you do?

    Show answer

    Read elements as Number; you can't add elements (except null).

    3

    What does PECS stand for? Apply it: a method that copies items from src into dst.

    Show answer

    Producer Extends, Consumer Super: copy(List<? extends T> src, List<? super T> dst).

    4

    Why is List<Object> not a good parameter type for "any list"?

    Show answer

    Invariance: a List<String> isn't a List<Object>, so it wouldn't accept one. Use List<?> (or a type parameter).