Summary of comparable and comparator differences in Java

Source: Internet
Author: User
Tags comparable

I. INTRODUCTION of comparable

Comparable is the sort interface. If a class implements the comparable interface, it means that the class supports sorting. A list or array of objects of a class that implements the comparable interface can be automatically sorted by Collections.sort or Arrays.sort.

In addition, objects that implement this interface can be used as a collection in a key or ordered collection in an ordered map without specifying a comparer. The interface is defined as follows:

 Package Java.lang; import java.util.*;  Public Interface Comparable<t>
Public int compareTo (T o);}

T represents the types of objects that can be compared with this object.

This interface has only one method, compare, to compare the order of this object with the specified object, and if the object is less than, equal to, or greater than the specified object, returns a negative integer, 0, or a positive integer, respectively.

Now let's assume a person class with the following code:

 Public classperson{String name; intAge ;  PublicPerson (String name,intAge ) {        Super();  This. Name =name;  This. Age =Age ; }     PublicString GetName () {returnname; }
Public intGetage () {returnAge ; }}

Now that there are two objects of the person class, how do we compare the size of the two? We can implement the comparable interface by having the person:

 Public classPersonImplementsComparable<person>{String name; intAge ;  PublicPerson (String name,intAge ) {        Super();  This. Name =name;  This. Age =Age ; }     PublicString GetName () {returnname; }     Public intGetage () {returnAge ; } @Override Public intcompareTo (person p) {return  This. age-P.getage (); }     Public Static voidMain (string[] args) {person[] people=Newperson[]{NewPerson ("Xujian", 20),NewPerson ("Xiewei", 10)}; System.out.println ("Before sorting");  for(person person:people) {System.out.print (Person.getname ()+":"+person.getage ());        } arrays.sort (people); System.out.println ("\ n Sort after");  for(person person:people) {System.out.print (Person.getname ()+":"+person.getage ()); }    }}

The results of the program execution are:

  

Ii. introduction of Comparator

Comparator is the comparison interface, if we need to control the order of a class, and the class itself does not support ordering (that is, does not implement the comparable interface), then we can create a "comparer of this class" to sort, this "comparator" You only need to implement the comparator interface. That is, we can create a new comparer by implementing comparator, and then sort the classes by this comparer. The interface is defined as follows:

 Package Java.util;  Public Interface comparator<t>intboolean  equals (Object obj);}

Note : 1, if a class to implement the comparator interface: it must implement the CompareTo (t O1, T O2) function, but can not implement the Equals (Object obj) function.

2, int compare (t O1, T O2) is "compare the size of O1 and O2". Returns "negative number", meaning "O1 is smaller than O2"; returning "0" means "O1 equals O2"; returning "positive number" means "O1 is greater than O2".

Now if the person class above does not implement the comparable interface, how to compare size? We can construct a "comparer" by creating a new class to implement the comparator interface.

 Public class Implements Comparator<person>{    @Override    publicint  Compare (person O1, person O2)    {        return o1.getage ()-o2.getage ();    }}

Now we can use this comparator to sort it:

 Public classperson{String name; intAge ;  PublicPerson (String name,intAge ) {        Super();  This. Name =name;  This. Age =Age ; }     PublicString GetName () {returnname; }     Public intGetage () {returnAge ; }     Public Static voidMain (string[] args) {person[] people=Newperson[]{NewPerson ("Xujian", 20),NewPerson ("Xiewei", 10)}; System.out.println ("Before sorting");  for(person person:people) {System.out.print (Person.getname ()+":"+person.getage ()); } arrays.sort (People,Newpersoncompartor ()); System.out.println ("\ n Sort after");  for(person person:people) {System.out.print (Person.getname ()+":"+person.getage ()); }    }}

The result of the program operation is:

  

Three, comparable and comparator difference comparison

Comparable is a sort interface, and if a class implements the comparable interface, it means "this class supports sorting." While comparator is a comparator, if we need to control the order of a class, we can create a "comparer for that class" to sort by.

Comparable is equivalent to an "internal comparator", while comparator is equivalent to an "external comparator".

Each of the two methods have advantages and disadvantages, with comparable simple, as long as the implementation of the comparable interface object directly becomes a comparable object, but need to modify the source code. The advantage of using comparator is that you do not need to modify the source code, but also to implement a comparator, when a custom object needs to be compared, the comparator and the object is passed together in the past can be compared to size, and in the comparator user can implement their own complex can be common logic, So that it can match some relatively simple objects, so that you can save a lot of duplication of work.

  

Summary of comparable and comparator differences in Java

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.