Reputation: 4732
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;
}
Upvotes: 4
Views: 1397
Reputation: 31
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.
Upvotes: 2
Reputation: 200206
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.
Upvotes: 3
Reputation: 14243
Upvotes: 3