Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

c# - Can someone explain what does <? super T> mean and when should it be used and how this construction should cooperate with <T> and <? extends T>?

I'm using generics rather long time but I've never used construction like List<? super T>.

What does it mean? How to use it? How does it look after erasure?

I also wonder: is it something standard in generic programming (template programming?) or it's just a java 'invention'? Does c#, for example, allow similar constructions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...