The difference between the Java.lang.Comparable interface and the Java.util.Comparator interface

Source: Internet
Author: User
Tags abs comparable java comparator

Java comparator and comparable when a collection or array that needs to be sorted is not a purely numeric type, you can typically use comparator or comparable to implement object sorting or custom sorting in a simple way.

1.Comparable Introduction:

Java.lang.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, CompareTo, 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 class Person{    String name;    int age;    public Person(String name, int age)    {        super();        this.name = name;        this.age = age;    }    public String getName()    {        return name;    }  public int getAge()    {        return age;    }}

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 class Person implements Comparable<Person>{    String name;    int age;    public Person(String name, int age)    {        super();        this.name = name;        this.age = age;    }    public String getName()    {        return name;    }    public int getAge()    {        return age;    }    @Override    public int compareTo(Person p)    {        return this.age-p.getAge();    }    public static void main(String[] args)    {        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};        System.out.println("排序前");        for (Person person : people)        {            System.out.print(person.getName()+":"+person.getAge());        }        Arrays.sort(people);        System.out.println("\n排序后");        for (Person person : people)        {            System.out.print(person.getName()+":"+person.getAge());        }    }}

The results of the program execution are:

2.Comparator Introduction

Java.util.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> {    int compare(T o1, T o2);    boolean equals(Object obj); }

Attention:

    1. If a class is to implement the comparator interface: it must implement the compare (T O1, T O2) function, but it can not implement the Equals (Object obj) function.
    2. int compare (t O1, T O2) is "Comparing 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 PersonCompartor implements Comparator<Person>{    @Override    public int compare(Person o1, Person o2)    {        return o1.getAge()-o2.getAge();    }}

Now we can use this comparator to sort it:

public class Person{    String name;    int age;    public Person(String name, int age)    {        super();        this.name = name;        this.age = age;    }    public String getName()    {        return name;    }    public int getAge()    {        return age;    }    public static void main(String[] args)    {        Person[] people=new Person[]{new Person("xujian", 20),new Person("xiewei", 10)};        System.out.println("排序前");        for (Person person : people)        {            System.out.print(person.getName()+":"+person.getAge());        }        Arrays.sort(people,new PersonCompartor());        System.out.println("\n排序后");        for (Person person : people)        {            System.out.print(person.getName()+":"+person.getAge());        }    }}

The result of the program operation is:

Using Comparator is the strategy mode (strategy design pattern), which does not change the object itself, but uses a policy object (strategy object) to change its behavior.

For example: you want to sort integers by absolute size, integer is not required, you do not need to modify the integer class (in fact, you can not do so) to change its sorting behavior, as long as the implementation of the Comparator interface object to achieve control of its ordering is OK.

import  java.util.*;public class AbsComparator implements Comparator{         public int compare(Object o1,   Object o2){           int v1 = Math.abs(((Integer)o1).intValue());           int v2 = Math.abs(((Integer)o2).intValue());           return v1 > v2 ? 1 : (v1 == v2 ? 0:-1);       }}

Comparison between 3.comparable and comparator

==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 "comparator of this 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.

Differences between the Java.lang.Comparable interface and the Java.util.Comparator interface

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.