Java TreeSet method example of sorting students by age and name

This paper describes the method of sorting students by age and name by Java TreeSet. Share with you for your reference, as follows:

compareTo

int compareTo(T o)

Compares the order of this object with the specified object. If the object is less than, equal to, or greater than the specified object, a negative integer, zero, or positive integer are returned, respectively.

The implementation class must ensure that there is a relationship of SGN (x.compareto (y)) = = - SGN (y.compareto (x)) for all x and y. (this means that if y.compareto (x) throws an exception, x.compareto (y) also throws an exception.)

The implementation class must also ensure that the relationship is transitive: (x.compareto (y) > 0 & & y.compareto (z) > 0) means x.compareto (z) > 0.

Finally, the implementer must ensure that x.compareto (y) = = 0 means that SGN (x.compareto (z)) = = SGN (y.compareto (z)) exists for all Z. This is highly recommended (x.compareto (y) = = 0) = = (x.equals (y)), but it is not strictly required. In general, any class that implements the comparable interface and violates this condition should clearly point out this fact. It is recommended to state: "note: this class has a natural ranking that is inconsistent with equals."

In the previous description, the symbol SGN (expression) specifies the Signum mathematical function, which returns one of - 1, 0 or 1 respectively according to whether the value of expression is negative, zero or positive.

Parameters:

O - object to compare.

return:

A negative integer, zero, or positive integer, depending on whether the object is less than, equal to, or greater than the specified object.

Throw:

ClassCastException - if the type of the specified object does not allow it to be compared with this object.

For more information about Java algorithms, readers who are interested can see the topics on this site: Java data structure and algorithm tutorial, summary of Java DOM node operation skills, summary of java file and directory operation skills, and summary of Java cache operation skills

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>