Comparable and CompareTo

Source: Internet
Author: User
Tags comparable

Comparable

1. What is the comparable interface?

This interface forces the overall ordering of the objects for each class that implements it. This sort is called the natural sort of the class, and the compareTo method of the class is called its natural comparison method . The list of objects (and arrays) that implement this interface can be automatically sorted by Collections.sort (and arrays.sort ). An object that implements this interface can be used as a key in an ordered map table or as an element in an ordered collection without specifying a comparer. It is strongly recommended (though not required) to make natural sorting consistent with equals. The so-called consistent with equals refers to each E1 and E2 of Class C , when and only if (E1.compareto (Object) e2 = = 0) with When E1.equals ((Object) E2) has the same Boolean value, the natural ordering of class C is called consistent with equals .

2. What method to implement

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, it returns a negative integer, 0, or a positive integer, respectively.
It is highly recommended (X.compareto (y) ==0) = = (X.equals (y)) this practice, but not strictly required. In general, any implementation of comparable interfaces and classes that violate this condition should clearly state this fact. It is recommended that: "NOTE: This class has a natural sort that is inconsistent with equals. ”
Parameter: O-The object to compare. Return:
        A negative integer, 0, or positive integer, depending on whether the object is less than, equal to, or greater than the specified object. Thrown:
        ClassCastException-If the type of the specified object does not allow it to be compared with this object.


The CompareTo method must be overridden in the implementation of the comparable interface. The code is as follows:
1  PackageDemo4;2 3  Public classPersonImplementsComparable<person>{4 PrivateString name;5 Private intAge ;6 Private Charsex;7 8  PublicPerson (String name,intAgeCharsex) {9     Super();Ten      This. Name =name; One      This. Age =Age ; A      This. Sex =sex; - } -  the /*(non-Javadoc) - * @see java.lang.object#tostring () -  */ - @Override +  PublicString toString () { -     return"Person [name=" + name + ", age=" + Age + ", sex=" + Sex + "]"; + } A 

When different sorting methods are used, the different Comparato methods are overridden. This corresponds to a different data type at //public int compareTo (person o) { - //return this.sex-o.sex; - - //public int compareTo (person o) { - //return This.name.compareTo (o.name); - in Public intcompareTo (Person o) { - return This. age-O.age; to } -}

The main program is as follows:
1  PackageDemo4;2 3 ImportJava.util.TreeSet;4 5  Public classTest {6  Public Static voidMain (string[] args) {7Treeset<person> TreeSet =NewTreeset<person>();8person P1 =NewPerson ("John Doe", 34, ' male ');9person P2 =NewPerson ("Zhang San", 23, ' female ');TenPerson P3 =NewPerson ("Harry", 13, ' no '); OnePerson P4 =NewPerson ("small two", 25, ' two '); A Treeset.add (p1); - Treeset.add (p2); - Treeset.add (p3); the Treeset.add (p4); -      -      for(person Person:treeset) { - System.out.println (person); +     } - } +}

The display results are sorted in dictionary order according to the selection sort



Comparable and CompareTo

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.