Analysis of comparable and comparator in Java

Source: Internet
Author: User
Tags comparable

TreeSet are generally used when comparing collection elements. For simple data types, TreeSet can be compared directly. But for complex data types, such as data types or classes that you define, you need to set the comparison and comparison rules yourself, and you need to use comparable and comparator.

1, comparable and comparator are used to implement the comparison and sorting of elements in the collection. But there are some differences:

(1) Comparable is a sort of method implementation defined within the set, located under Java.util. The comparator is implemented on the outside of the collection, and the sort is located under Java.lang. So if you want to sort the collection, you need to define a method for the comparator interface outside the collection or a method that implements the comparable interface within the collection.

(2) Comparable is an object itself has been supported by the implementation of self-comparison interface, such as String, integer itself to implement the comparable interface, you can complete the comparison size operation. Custom classes can be sorted after being added to the list container, or the comparable interface may be implemented, and if comparator is not specified in the sort method of the collections class, it is sorted in a natural order. The so-called natural order is the implementation of the comparable interface settings of the ordering mode.
Simply put, a class implementation of the comparable interface indicates that objects of this class can be compared to each other, and the combination of such objects can be sorted directly using the Sort method.

(3) Comparator is a dedicated comparator, and when the object does not support self-comparison or the self-comparison function does not meet the requirements, a comparator can be written to complete the comparison of the size between the two objects. Comparator embodies a strategy pattern (strategy design pattern) that does not change the object itself, but uses a policy object (strategy object) to change its behavior, separating the algorithm from the data. Comparator can also be used in the following two environments:

    • Class is not designed with a comparison problem in mind and does not implement the comparable interface, it can be sorted by comparator without having to modify the original class code.
    • The comparable interface is implemented in class design, but later users want to compare classes with a new comparison rule

2. Example
(1) Comparable sorting

Package Com.collection;import java.util.Objects; Public classItem Implements comparable<item>{PrivateString description;Private intPartNumber; Public Item(String adescription,intApartnumber) {description = Adescription;    PartNumber = Apartnumber; } PublicStringgetdescription()    {returnDescription } PublicStringtoString()    {return "[description=]+description+", partnumber="+partnumber+"]"; } PublicBooleanequals(Object Otherobject) {if( This= = Otherobject)return true;if(Otherobject = =NULL)return false;if(GetClass ()!=otherobject.getclass ())return false; Item other = (item) Otherobject;returnObjects.equals (description, other.description) &&partnumber = = Other.partnumber; } Public int hashcode()    {returnObjects.hash (Description,partnumber); }//Overload CompareTo method, set the comparison method for the item object@Override Public int CompareTo(Item Other) {returnInteger.compare (PartNumber, Other.partnumber); }}

(2) comprehensive comparable and comparator

//Implement comparable interface Public classPerson implements comparable<object>{Private intNumPrivateString name;Private intAge Public  Person(intNum, String name,intAge) {super (); This. num = num; This. name = name; This. Age = Age;} Public int CompareTo(Object o) {return  This. Age-(person) O). Getage ();} Public int Getnum(){returnNum;} Public void Setnum(intNUM) { This. num = num;} PublicStringGetName(){returnName;} Public void SetName(String name) { This. name = name;} Public int Getage(){returnAge;} Public void Setage(intAge) { This. Age = Age;}}//Implement Comparator interface Public classPersoncomparator implements comparator<object>{@Override Public int Compare(Object O1, Object O2) {intNUM1 = (person) O1). Getnum ();intnum2 = (person) O2). Getnum ();returnNum1 > num2?1: (NUM1 = = num2?)0: -1);}}//Test Public classpersontest{ Public Static void Main(string[] args) {Person P1 =NewPerson (1,"Xy1", A); person P2 =NewPerson (2,"Xy1", +); System. out. println ("Implementing the Comparable interface method result (by age comparison):");//result is 1System. out. println (P1.compareto (p2)); System. out. println ("Implementing the Comparator interface method result (by the number of studies):");//result is-1Personcomparator PC =NewPersoncomparator (); System. out. println (Pc.compare (P1, p2));///can also be used to declare a person[] PS, sorted by Array.Sort (PS)}}

Analysis of comparable and comparator in Java

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.