Differences between Comparable and Comparator

Source: Internet
Author: User

Differences between Comparable and Comparator

 

 

Both Comparable and Comparator are used to compare and sort elements in a set,Comparable is inside the setSorting of defined methods,Comparator is outside the setSo, to achieve sorting, You need to define the Comparator interface method outside the set or implement the Comparable interface method in the set.

Comparator is located under the java. util package, while Comparable is located under the java. lang package.

Comparable is an interface that the object itself must implement to support self-comparison (for example, the String and Integer operations can be completed by themselves, and the Comparable interface has been implemented)

A custom class can be sorted after being added to the list container. You can implement the Comparable interface. If you do not specify a Comparator when using the sort method of the Collections class, sort the data in a natural order, as the API says:

Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface

The natural order here is the sorting method set by the Comparable interface.

Comparator is a dedicated Comparator. When this object does not support auto-comparison or the auto-comparison function cannot meet your requirements, you can write a Comparator to compare the sizes of two objects.

It can be said that the comparison is done by yourself, and the comparison is made by external programs.

Using Comparator is a strategy design pattern. Instead of changing the object itself, a strategy object is used to change its behavior.

Comparable interface

For example, if we define a Country class, we want its objects to have a size relationship and sort by countryId, so we let Country implement the Comparable interface to make it have a size relationship, the Code is as follows:

class Country implements Comparable{    private int countryId ;    @Override    public int compareTo(Object o) {        Country country = (Country)o ;        return this.getCountryId()>country.getCountryId()?1:this.getCountryId()==                country.getCountryId()?0:-1 ;    }}

In this case, Country has the ability to compare, just like the Integer and String classes. In this case, the set of Country objects can be Collections. sort (), or Arrays. to sort.

Next, let's take a look at how Comparator implements it.

Comparator interface

As we have said before, Comparator is actually like a tool. It does not make Country sort, but does not change the Country class itself. Instead, it implements a sort tool separately, to be provided to Country. Next we will implement this sorting tool class.

class Country{    private int id ;    public Country(int id){        this.id = id ;    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }}class CountryByIdComparator implements Comparator
  
   {    @Override    public int compare(Country o1, Country o2) {        return o1.getId()>o2.getId()?1:o1.getId()==o2.getId()?0:-1 ;    }}
  

You have noticed that the Country class does not have any relationship with the comparison, but it can achieve automatic sorting by implementing the tool class ContryByIdComparator that the Comparator excuses. At this time, the called Collections. sort () requires two parameters: a set and a tool class that implements the Comparator interface.

We can also use anonymous internal classes instead of defining a tool class such as ContryByIdComparator. The Code is as follows:

Collections.sort(cityList,new Comparator
  
   (){            @Override            public int compare(City o1, City o2) {                return o1.getId()>o2.getId()?1:o1.getId()==o2.getId()?0:-1 ;            }        }) ;
  

Comparator is a strategy design pattern. Instead of changing the object itself, Comparator uses a strategy object to change its behavior.

The following figure shows the differences between them:

Refference

  1. Difference between Comparable and Comparator Difference between Comparator and Comparable in Java

    17:27:25

    Brave, Happy, Thanksgiving!

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.