Java comparable and comparator

Source: Internet
Author: User
Tags comparable

In Java, when sorting data, comparable and comparator are not needed to be met. Ordinary string, integer and other types have implemented the comparable interface, and sometimes we need to sort some other classes that do not have an intrinsic sort relationship, then we need to implement the above two interfaces, but it will be different.

Before searching for the relationship between the two. See such an article. The difference between comparable and comparator, some of which are a bit too esoteric, but I would like to summarize the words. the biggest difference between the two is that assuming the implementation of comparable means that the collation of the class is fixed, and that the class itself is not sorted by the implementation of comparator, but simply by making an external rule to sort it, you can specify very many types .

So let's take a look at my example, and we'll create a new beauty Class (Beautygirl). The way to do this is to have the age, height property, and so on, to sort according to the principle that age takes precedence over height.

Comparable
 Packagecom.mwq.comparable; Public  class beautygirl implements comparable<beautygirl> {    Private intAgePrivateDouble height; Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; } PublicDoublegetheight() {returnHeight } Public void setheight(Double height) { This. height = height; }@Override     Public int CompareTo(Beautygirl Girl) {if( This. getage () = = Girl.getage ()) {returnCompareheight (girl); }Else{return  This. Getage ()-girl.getage (); }    }Private int Compareheight(Beautygirl Girl) {returnGirl.getheight (). CompareTo ( This. GetHeight ()); }@Override     PublicStringtoString() {return "Beauty {age:"+ This. Getage () +"Height:"+ This. GetHeight () +"}"; }}

Implementing the comparable interface means implementing the CompareTo method in the beauty class, which means that the class must be age-first over height when sorting.

Take a look at the test class.

 Packagecom.mwq.comparable;ImportJava.util.ArrayList;ImportJava.util.Collections;ImportJava.util.List; Public  class Test {     Public Static void Main(string[] args) {List<beautygirl> girls =NewArraylist<beautygirl> (); Beautygirl girl =NewBeautygirl (); Girl.setage ( -); Girl.setheight (170.00);        Girls.add (girl); Girl =NewBeautygirl (); Girl.setage ( -); Girl.setheight (183.00);        Girls.add (girl); Girl =NewBeautygirl (); Girl.setage ( -); Girl.setheight (180.30);        Girls.add (girl); Girl =NewBeautygirl (); Girl.setage ( +); Girl.setheight (170.00);        Girls.add (girl); Girl =NewBeautygirl (); Girl.setage ( +); Girl.setheight (170.00); Girls.add (girl); for(Beautygirl beautygirl:girls)        {System.out.println (beautygirl);        } collections.sort (girls); System.out.println ("Sort---------------------------------------------"); for(Beautygirl beautygirl:girls)        {System.out.println (beautygirl); }    }}

the output results are as follows :

美女{年龄:28身高:170.0}美女{年龄:25身高:183.0}美女{年龄:28身高:180.3}美女{年龄:32身高:170.0}美女{年龄:21身高:170.0}排序一下---------------------------------------------美女{年龄:21身高:170.0}美女{年龄:25身高:183.0}美女{年龄:28身高:170.0}美女{年龄:28身高:180.3}美女{年龄:32身高:170.0}
Comparator
 PackageCom.mwq.comparator; Public  class beautygirl {    Private intAgePrivateDouble height; Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; } PublicDoublegetheight() {returnHeight } Public void setheight(Double height) { This. height = height; }@Override     PublicStringtoString() {return "Beauty {age:"+ This. Getage () +"Height:"+ This. GetHeight () +"}"; }}
 PackageCom.mwq.comparator;ImportJava.util.Comparator;/** * Achieve the beauty of the sort * * Public  class beautygirlcomparator implements Comparator<beautygirl > {    @Override     Public int Compare(Beautygirl girl1, Beautygirl girl2) {//Put your age first        if(Girl1.getage () = = Girl2.getage ()) {returnCompareheight (GIRL1, GIRL2); }Else{returnGirl1.getage ()-girl2.getage (); }    }Private int Compareheight(Beautygirl girl1, Beautygirl girl2) {//Put your height in the second place        returnGirl1.getheight (). CompareTo (Girl2.getheight ()); }}
new BeautyGirlComparator());

This is when you use sort, and you just need to specify a new rule that will be sorted according to the new rules, without the need to change the Beautygirl class.

Like what. You can sort by height preference and age.

Summary : The difference between the two lies in the formulation of the collation. Suppose the collation is fickle. It is a good idea to use comparator, assuming that the rules are fixed, that the comparable is better, and at least one less class is written.

Java comparable and comparator

Related Article

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.