The details and distinctions of Java comparable and Comparator _java

Source: Internet
Author: User
Tags arrays comparable

The details and differences of Java comparable and Comparator

Java provides us with two comparison mechanisms: comparable and Comparator, what is the difference between them? Come to understand today.

Comparable natural sort

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

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

Comparable allows you to compare the objects of the classes that implement it, and the specific comparison rules are based on the rules in the CompareTo method. This order is called the natural order.

The return value of the CompareTo method has three different scenarios:

    1. E1.compareto (E2) > 0 that is e1 > E2
    2. E1.compareto (e2) = 0 = E1 = E2
    3. E1.compareto (E2) < 0 that is E1 < E2

Attention:

1. Because 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 Method should also actively throw a null pointer exception nullpointerexception.

The 2.Comparable implementation class overrides the CompareTo method generally requires that the result of E1.compareto (e2) = = 0 be consistent with E1.equals (E2). This enables future use of the collection container, which is sorted by the natural sort of the class, to ensure that the stored data is in the same order as SortedSet.
One might wonder what would happen if the 2nd above was violated?

For example, if you add two objects A and B,a B to a sortedset (!a.equals (b) && A.compareto (b) = 0), and there is no additional Comparator specified, then when you have finished adding a Adding B will add a failure return false, SortedSet size will not increase, because in sortedset it appears that they are the same, and SortedSet is not allowed to repeat.

In fact, all the Java core classes that implement the comparable interface have the same results as the Equlas method.
The List or array that implements the comparable interface can be sorted using the Collections.sort () or Arrays.sort () method.

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

Therefore, if you define a class to use an ordered collection class, you need to implement the comparable interface, such as:

* * Description: Test of the entity of the encyclopedia, the realization of the comparable interface, natural sort * <br/> * Author:shixinzhang * <br/> * DATA:10/5/2
  016 */public class Bookbean implements Serializable, comparable {private String name;


  private int count;
    Public Bookbean (String name, int count) {this.name = name;
  This.count = count;
  Public String GetName () {return name;
  public void SetName (String name) {this.name = name;
  public int GetCount () {return count;
  public void SetCount (int count) {This.count = count; /** * override 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 ()); /** * Rewrite hashcode calculation method * Iterative calculation based on all properties to avoid repetition * calculation of hashcode when calculating factor 31 is a prime number and cannot be removed @return * *Override public int hashcode () {//Call String's Hashcode (), uniquely represents a string content int result = GetName (). Hashcode ();
    Multiplied 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 Compar
      ETo (Object another) {if (another instanceof Bookbean) {Bookbean Anotherbook = (Bookbean) another;

      int result;   

     For example, this is sorted by book price result = GetCount ()-Anotherbook.getcount ();

      Alternatively,//result = GetName (). CompareTo (Anotherbook.getname ()) in the comparison order of String. if (result = = 0) {//when the book price is the same, compare the title.
      Ensure that all properties are compared again result = GetName (). CompareTo (Anotherbook.getname ());
    return result;
  //return 0 returns 0;

 }

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

When you rewrite CompareTo later, you can compare the next property to one of the same times, comparing all the properties.

The comparable interface is part of the Java collection framework.

Comparator Custom Sort

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

Public interface Comparator<t> {public

  int compare (t LHS, t RHS);

  public boolean equals (object);


After JDK 1.8, there are a number of additional methods:

Basically is related to Function, here is not to introduce 1.8 new.

From the above, it is known that using natural sorting requires class implementation comparable and rewriting Comparato methods internally.

Instead, Comparator sets the collation outside and passes it as a sort policy parameter to some classes, such as Collections.sort (), Arrays.sort (), or some internally ordered collection (such as Sortedset,sortedmap).

The way of use is mainly divided into three steps:

1. Create an implementation class for the Comparator interface and assign a value to an object

Write a collation for a custom class in the Compare method

2. A method that passes the Comparator object as a parameter to the sort class

3. Add the custom class used in the Compare method to the Sort class

As an example:

 1. Create an object that implements the Comparator interface
    Comparator Comparator = new Comparator () {
      @Override public
      int compare (Object o Bject1, Object object2) {
        if (object1 instanceof newbookbean && object2 instanceof Newbookbean) {
          Newbookbean Newbookbean = (Newbookbean) object1;
          Newbookbean newBookBean1 = (Newbookbean) object2;
          The specific comparison method refers to the CompareTo method of natural ordering, where only a chestnut return
          newbookbean.getcount ()-Newbookbean1.getcount ();
        }
        return 0;
      }
    ;

    2. Pass this object as a parameter to the constructor of the TreeSet
    TreeSet TreeSet = new TreeSet (comparator);

    3. Add the Object
    treeset.add (New Newbookbean ("A", TreeSet) to the class that is designed in the Compare method in step 1;
    Treeset.add (New Newbookbean ("S", 1));
    Treeset.add (New Newbookbean ("V",));
    Treeset.add (New Newbookbean ("Q", 26));

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

A reference that holds a Comparator interface in the Sort class:

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.

Summarize

Two ways to sort in Java:

Comparable natural sort. (Entity class implementation)
Comparator is a custom sort. (When entity classes cannot be modified, they are created directly on the caller)

Comparisons are made by Comparator (custom sort) rules that exist simultaneously.

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 in different situations, and we can create a new Comparator interface and compare it with a specific Comparator implementation.

This is the difference between comparable and Comparator.

Thank you for reading, I hope to help you, thank you for your support for this site!

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.