Question

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;
}
Was it helpful?

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.

OTHER TIPS

  • Producer refers to the return type of a method.
  • Consumer refers to the parameter type of a method.

The following cleared things up a bit in my mind. Hope it helps you.

Imagine a list of elements of some unknown type X and there is some logic some where that scans the list as elements of type X explicitly (after the list is built). Lets call this logic Logic1.

If you are going to scan that list as objects of type T, there is a requirement that X be derived from T in some form. Otherwise, you will have problems. Hence your signature should be:

void scan(List<? extends T>);

If you are going to add objects of type T to the list, there is a requirement that T be derived from X. Otherwise Logic1 mentioned above will have problems. Hence your signature should be:

void add(List<? super T>);

Note that it is my understanding that both "scan" and "add" can actually remove entries from the list. I find PECS to be a little confusing. The "producer" and "consumer" comes from the perspective of the list. I don't like to look at list as active thing that can execute logic. I like SEAS (Scan Extends and Add Supers). Just my 2 cents.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top