Comparable and Comparator in java

Source: Internet
Author: User

Comparable and Comparator in java

Comparable and Comparator in java

 

-Comparable Interface

 

Interface Definition

 

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

 

This interface only contains a compareTO () function,

 

 

Int compareTo (Object o): compares the current instance Object with the Object o. If it is before the Object o, a negative value is returned. If the two objects are in the same position in the sorting, 0 is returned, if it is behind object o, a positive value is returned.

 

Instance: x. compareTo (y) to "compare the size of x and y ". If "negative" is returned, it means "x is smaller than y". If "zero" is returned, it means "x is equal to y". If "positive" is returned, it means "x is greater than y ".

 

How to Use: Since the Comparable interface defines the natural sequence of classes, classes that implement this interface can be sorted in this way. (That is, you can directly call the. sort () method for sorting)

 

For example:

package bolg;public class Person implements Comparable{    String name;    int age;    Person(String name,int age)    {        this.name=name;        this.age=age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public int compareTo(Object o) {        // TODO Auto-generated method stub        int i = 0;        i=name.compareTo(((Person)o).name);        if(0==i)        {            return age-((Person)o).age;        }        else {            return i;        }    }}

Test

package bolg;import java.util.Arrays;public class TestPerson {    public static void   main(String args[])    {     Person[] persons = new Person[] { new Person("a", 30), new Person("ab", 20) };        Arrays.sort(persons);        for (int i = 0; i < persons.length; i++) {            Person user = persons[i];          System.out.println(user.getName() + " " + user.getAge());        }    }}

Output result

a 30ab 20
-Comparator Interface

 

The interface is defined as follows:

 

public interface Comparator
  
    {     int compare(T o1, T o2);     boolean equals(Object obj);  } 
  

 

(01) If a class needs to implement the Comparator interface: it must implement the compareTo (T 1, T 2) function, but it can not implement the equals (Object obj) function.

 

Why not implement the equals (Object obj) function? By default, equals (Object obj) has been implemented for any class. All classes in Java are inherited from java. lang. object, in the Object. java implements the equals (Object obj) function. Therefore, all other classes also implement this function.

 

(02) int compare (T o1, T o2) is "comparing the size of o1 and o2 ". Return "negative number", which means "o1 is smaller than o2"; Return "zero", which means "o1 is equal to o2"; Return "positive number", which means "o1 is greater than o2 ".

 

 

How to Use: Comparator can be seen as an algorithm implementation that separates algorithms from data. Comparator can also be used in the following two environments:

 

  • 1. Category designers do not consider comparison issues and do not implement Comparable. You can use Comparator to sort objects without changing the object itself.
  • 2. Multiple sorting criteria can be used, such as ascending or descending order.

     

    Instance to implement a comparator that only sorts by age

     

    package bolg;import java.util.Comparator;public class PersonComparator implements Comparator{    @Override    public int compare(Object o1, Object o2) {        // TODO Auto-generated method stub              return ((Person) o1).getAge() - ((Person) o2).getAge();    }}
    package bolg;import java.util.Arrays;public class TestPerson {    public static void   main(String args[])    {     Person[] persons = new Person[] { new Person("a", 30), new Person("ab", 20) };      //  Arrays.sort(persons);    Arrays.sort(persons,new PersonComparator());        for (int i = 0; i < persons.length; i++) {            Person user = persons[i];          System.out.println(user.getName() + " " + user.getAge());        }    }}

     

    Output result

     

    ab 20a 30
    -Comparison between Comparable and Comparator

     

    Comparable forcibly sorts the objects of each class. This sort is called the natural sorting of classes, and the compareTo method of classes is called its natural comparison method. Objects (and Arrays) that implement this interface can be automatically sorted by Collections. sort (and Arrays. sort. The object implementing this interface can be used as a key or element in an ordered set in an ordered ing without specifying a comparator.

     

     

    Comparator is a comparison function that forcibly sorts an object collection. Comparator can be passed to the sort method (such as Collections. sort or Arrays. sort) to allow precise control over the sorting order. You can also use Comparator to control the order of certain data structures (such as ordered set or ordered ing), or provide sorting for object collections without natural order. The idea is actually in the java design model ----Rule-Based Mode

     

     

    Summary: The two methods have their own advantages and disadvantages. Comparable is simple. As long as the object implementing the Comparable interface becomes a Comparable object, you need to modify the source code, the advantage of using Comparator is that you do not need to modify the source code, but implement another Comparator. When a custom object needs to be compared, you can pass the Comparator and object together to compare the size, in addition, in the Comparator, users can implement complex universal logic by themselves, so that they can match some simple objects, which can save a lot of repetitive work.

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.