Search code examples
javagenericswildcardpecs

Java generics PECS


I know what is the meaning of PECS.

Producer Extends,Consumer Super.

the thing is how would I know if its a consumer or producer?

Also does this code follow the "PECS"

public class Tree<T> {

    //List of branches for this tree
    private List<Tree<? super T>> branch = new ArrayList<Tree<? super T>>();
    public Tree(T t){ this.t = t; }
    public void addBranch(Tree< ? super T> src){ branch.add(src); }
    public Tree<? extends T> getBranch(int branchNum){
        return (Tree<? extends T>) branch.get(branchNum);
    }
    private T t;
}

Solution

  • A nice mnemonic you can use is to imagine returns for extends and accepts for super.

    So a Tree<? extends T> reads Tree<? returns T>, which means that you can call the methods in Tree that return T, but not the methods that accept T as an argument type.