? The super t syntax limits generic classes to all t superclasses (including T itself). However, they can only be used in parameters and cannot be used in return values.
If not specified, assume that a function header is
? Super manager get ()
Since the compiler does not know what class the method will return, it can only be received using the object class.
A common case of this syntax is the comparison of generic classes.
Java. util. treeset <E> indicates a tree with an ordered Element E. One of its constructors needs a comparator class to compare two elements. Take E as a string class as an example, in this case, comparator can be comparator <string> or comparator <Object>, but comparator <integer> cannot be used. How can this restriction be expressed?
JDKSource codeIs as follows:
Public treeset (comparator <? Super E> C)
This ensures that the comparator passed to the constructor can compare the eElements.
In another example, the max method of Java. util. collections is used to obtain the maximum value in a container. This function header can be written as follows:
Public static <t extends comparable <t> T max (collection <t> Coll)
In this way, T is a class that can be compared with itself, which is too strict. The JDK source code is as follows:
Public Static < T Extends Object & Comparable <? Super T > T max (Collection <? Extends T > Coll) {
Iterator <? Extends T > I = Coll. iterator ();
T candidate = I. Next ();
While (I. hasnext ()) {
T next=I. Next ();
If(Next. compareto (candidate)> 0)
Candidate=Next;
}
Return Candidate;
}
Very rigorous function header, but the limitation is relatively wide