Java FAQ: The difference between comparable and Comparator

Source: Internet
Author: User
Tags comparable object object

Tag: null override cannot serial failed RBO entity i++ data

After reading this article you will learn:

      • Comparable natural sort
      • Comparator Custom Sorting
      • Summarize

There are two comparison mechanisms available in Java: Comparable and Comparator, what's the difference between them? Come and find out today.

Comparable natural sort

Comparable under the Java.lang package, is an interface with only one method inside CompareTo ():

public interface Comparable<T> {    public int compareTo(T o);}

The comparable can be used to compare the objects of the class that implements it, and the specific rules of comparison are made according to the rules in the CompareTo method. This order is called the natural order .

There are three conditions for the return value of the CompareTo method:

    • E1.compareto (E2) > 0 E1 > E2
    • E1.compareto (e2) = 0 = E1 = E2
    • E1.compareto (E2) < 0 E1 < E2


1. Since null is not a class and is not an object, you should be aware of e.compareto (null) When overriding the CompareTo method, even if e.equals (null) returns False,compareto The method should also actively throw a null pointer to the exception nullpointerexception.

The 2.Comparable implementation class overrides the CompareTo method generally requires that the results of e1.compareto (e2) = = 0 be consistent with E1.equals (E2). In this way, the collection containers that are sorted by the natural sort of the class, such as SortedSet, can be used to ensure that the order of the saved data is consistent with the imagination.

One might wonder what would happen if the 2nd was violated.

For example, if you add two objects A and B,a B to a SortedSet (!a.equals (b) && A.compareto (b) = = 0) without specifying a Comparator, then when you add a Adding b adds the failure to return false, and the size of the SortedSet does not increase because in SortedSet it appears they are the same, and SortedSet is not allowed to repeat.

Virtually all Java core classes that implement the comparable interface have the same results as the Equlas method.
A List or array that implements the comparable interface can be used Collections.sort() or Arrays.sort() sorted by method.

An object that implements the comparable interface can be used directly as a key for SortedMap (SortedSet), otherwise the Comparator collation must be specified outside.

Therefore, if you want to use an ordered collection class for your own class, you need to implement the comparable interface, such as:

* * Description: Test of the Entity book, the implementation of the comparable interface, natural sort * <br/> * Author:shixinzhang * <br/> * data:10/5/2016 * *    public class Bookbean implements Serializable, comparable {private String name;    private int count;        Public Bookbean (String name, int count) { = name;    This.count = count;    } public String GetName () {return name;    } public void SetName (String name) { = name;    } public int GetCount () {return count;    } public void SetCount (int count) {This.count = count; }/** * Overrides equals * @param o * @return */@Override public boolean equals (Object o) {if (        this = = O) return true; if (! (        o instanceof Bookbean)) return false;        Bookbean bean = (bookbean) o;        if (GetCount () = Bean.getcount ()) return false;    Return GetName (). Equals (Bean.getname ()); }/** * Override Hashcode calculation method * Iterative calculation based on all attributes, avoid repetition * calculate factor 31 when calculating hashcodeMuch, is a prime number, can no longer be removed * @return */@Override public int hashcode () {//Call string Hashcode (), uniquely represents a string content        int result = GetName (). Hashcode ();        Multiply by 31, plus count result = * result + GetCount ();    return result;                } @Override Public String toString () {return ' bookbean{' + ' name= ' "+ name + ' \ ' +    ", count=" + Count + '} '; /** * When adding Bookbean to TreeSet, this method is called to sort * @param another * @return */@Override public int             CompareTo (Object another) {if (another instanceof Bookbean) {Bookbean Anotherbook = (Bookbean) another;            int result;               For example here according to book price order result = GetCount ()-Anotherbook.getcount ();            Or in the order of comparison of strings//result = GetName (). CompareTo (Anotherbook.getname ()); if (result = = 0) {//when the book price is the same, then compare the title. Ensure that all attributes are compared once to result = GetName (). CompareTo (Anotherbook.getname ());        } return result;    }//returns 0 return 0; }

The above code also overrides the Equlas (), Hashcode () method, which is overridden by custom classes that want to be compared.

When you rewrite CompareTo later, you can compare all of the attributes once by judging the next property in the same time.

The comparable interface is part of the Java collection framework.

Comparator Custom Sorting

Comparator is also an interface under the Java.util package, and JDK 1.8 had only two methods:

public interface Comparator<T> {    public int compare(T lhs, T rhs);    public boolean equals(Object object);}

JDK 1.8 Adds a number of new methods:

Basically are related to Function, here is not introduced 1.8 new.

From the above, it is known that using natural sorting requires the class to implement comparable and internally override the Comparato method.

The Comparator, however, is to create a collation externally and then pass it as a sort policy parameter to some classes, such as Collections.sort (), Arrays.sort (), or some internally ordered collection (such as SORTEDSET,SORTEDMAP, etc.).

There are three main ways of using it:

    1. Create an implementation class for the Comparator interface and assign a value to an object
      • Write collations for custom classes in the Compare method
    2. To pass a Comparator object as a parameter to a method of the Sort class
    3. To add a custom class to the sort class that is used in the Compare method

As an example:

 //1. Create an object that implements the Comparator interface Comparator Comparator = new Comparator () {@Override public int Compare (object Object1, Object Object2) {if (Object1 instanceof Newbookbean &&                    Object2 instanceof Newbookbean) {Newbookbean Newbookbean = (Newbookbean) Object1;                    Newbookbean newBookBean1 = (Newbookbean) object2;                The specific comparison method refers to the natural ordering of the CompareTo method, here only a chestnut return Newbookbean.getcount ()-Newbookbean1.getcount ();            } return 0;        }        };        2. Pass this object as a parameter to the constructor of TreeSet TreeSet TreeSet = new TreeSet (comparator);        3. Add the Object Treeset.add (new Newbookbean ("A", 34) of the class designed in the Compare method in step 1 to TreeSet);        Treeset.add (New Newbookbean ("S", 1));        Treeset.add (New Newbookbean ("V", 46)); Treeset.add (New Newbookbean ("Q", +));  

In fact, it can be seen that the use of Comparator is a strategy model, unfamiliar with the strategy model of the students can click here to view: Strategy mode: Network novel fixed routines to understand.

The sort class holds a reference to a Comparator interface:

Comparator<? super K> comparator;

Instead, we can pass in the Comparator implementation classes of various custom collations and make different sorting strategies for the same classes.


Two ways to sort in Java:

    1. Comparable natural sort. (Entity class implementation)
    2. Comparator is a custom sort. (When an entity class cannot be modified, it is created directly on the caller)

At the same time, the rules are compared using Comparator (custom sort).

For some common data types (such as String, Integer, Double ...). ), they implement the comparable interface by default and implement the CompareTo method, which we can use directly.

For some custom classes, they may need to implement different comparison strategies under different circumstances, and we can create a new Comparator interface and compare it with a specific Comparator implementation.

This is the difference between comparable and Comparator.

Java FAQ: The difference between 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: 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.