Java - Wildcard Example - super vs extends

Subscribe Send me a message home page tags


In this post, we will provide a concrete exmple to explain "producer extends, consumer super".
public class WildCardExample {

    // Part 1: Consumer super
    // In this part, the colleciton variable is a consumer of the element of type T.

    public static <T> void extendsBlocksWrite(Collection<? extends T> c, T element) {
        // extends blocks write. The code below cannot compile.
        // Collection<? super T> means the element in c requires more information than T.
        // The element of type T contains less information than required, therefore, we cannot
        // add the variable element to the list.
        c.add(element); // Cannot compile.
    }

    public static <T> void g(Collection<? super T> c, T element) {
        // Collection<? super T> means the element in c requires less information than T.
        // Therefore, we can add the element of type T to the collection as it contains more
        // information than required.
        c.add(element);
    }

    // Part 2: Producer extends.
    // In this part, the list will produce an element of type T.

    public static <T> T h(List<? extends T> c) {
        // List<? extends T> c means the element in the list contains more information than T.
        // This method needs to return an instance that can provide T information, therefore
        // the element in the list satisfies this requirement.
        return c.get(0);
    }

    public static <T> T superBlocksRead(List<? super T> c) {
        // super blocks read. The code below cannot compile.
        // Collection<? super T> means the element in c requires less information than T. And
        // this method needs to return an instance that can provide T information. Therefore,
        // the element in the list does not satisfy the requirement.
        return c.get(0); // Cannot compile.
    }
}

----- END -----

Welcome to join reddit self-learning community.
Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png