This construct is used when you want to consume items from a collection into another collection. E.g. you have a generic Stack
and you want to add a popAll
method which takes a Collection as parameter, and pops all items from the stack into it. By common sense, this code should be legal:
Stack<Number> numberStack = new Stack<Number>();
Collection<Object> objects = ... ;
numberStack.popAll(objects);
but it compiles only if you define popAll
like this:
// Wildcard type for parameter that serves as an E consumer
public void popAll(Collection<? super E> dst) {
while (!isEmpty())
dst.add(pop());
}
The other side of the coin is that pushAll
should be defined like this:
// Wildcard type for parameter that serves as an E producer
public void pushAll(Iterable<? extends E> src) {
for (E e : src)
push(e);
}
Update: Josh Bloch propagates this mnemonic to help you remember which wildcard type to use:
PECS stands for producer-extends, consumer-super.
For more details, see Effective Java 2nd Ed., Item 28.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…