In Java generics? Super t syntax

Source: Internet
Author: User
Tags comparable

? 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.