Comparable and comparator in Java

Source: Internet
Author: User
Tags comparable

comparable and comparator in Java

-comparable interface

Interface definition

publicinterface Comparable<T> {     publicint compareTo(T o);  }  

The interface contains only one CompareTo () function,

int CompareTo (object o): Compares the current instance object with the object o, returns a negative value if it precedes the object o, returns 0 if two objects are in the same position in the sort, and returns a positive value if it is behind the object o.

    实例:    x.compareTo(y) 来“比较x和y的大小”。若返回“负数”,意味着“x比y小”;返回“零”,意味着“x等于y”;返回“正数”,意味着“x大于y”。

How to use: Because the comparable interface defines the natural order of the class, classes that implement the interface can be sorted in this manner. (That is, you can directly invoke the. Sort () method to achieve sorting)

Such as:

 PackageBolg Public  class  person implements comparable{String name;intAge Person (String name,intAge) { This. name=name; This. age=age; } PublicString GetName () {returnName } Public voidSetName (String name) { This. name = name; } Public intGetage () {returnAge } Public voidSetage (intAge) { This. Age = Age; }@Override     Public intCompareTo (Object o) {//TODO auto-generated method stub        inti =0; I=name.compareto ((person) o). Name);if(0==i) {returnage-(person) O). Age; }Else{returnI }    }}

Test

 PackageBolgImportJava.util.Arrays; Public  class Testperson {     Public Static voidMain (String args[]) {person[] persons =NewPerson[] {NewPerson ("a", -),NewPerson ("AB", -) }; Arrays.sort (persons); for(inti =0; i < persons.length;          i++) {Person user = persons[i]; System.out.println (User.getname () +" "+ user.getage ()); }    }}

Output results

a 30ab 20
-comparator interface

The interface is defined as follows

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

(01) If a class is 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.

    为什么可以不实现 equals(Object obj) 函数呢? 因为任何类,默认都是已经实现了equals(Object obj)的。 Java中的一切类都是继承于java.lang.Object,在Object.java中实现了equals(Object obj)函数;所以,其它所有的类也相当于都实现了该函数。

() 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".

How to use: Comparator can be regarded as an algorithm implementation, the algorithm and data separation, comparator can also be used in the following two kinds of environments:

    • 1, the designer of the class did not consider the comparison problem and did not implement comparable, can be comparator to achieve the sort without having to change the object itself
    • 2, can use a variety of sorting criteria, such as ascending, descending, etc.

instance, implement a comparator, sort by age only

 PackageBolgImportJava.util.Comparator; Public  class personcomparator implements Comparator{    @Override     Public intCompare (Object o1, Object o2) {//TODO auto-generated method stub        return(person) O1). Getage ()-((person) O2). Getage (); }}
 PackageBolgImportJava.util.Arrays; Public  class Testperson {     Public Static voidMain (String args[]) {person[] persons =NewPerson[] {NewPerson ("a", -),NewPerson ("AB", -) };//Arrays.sort (persons);Arrays.sort (Persons,NewPersoncomparator ()); for(inti =0; i < persons.length;          i++) {Person user = persons[i]; System.out.println (User.getname () +" "+ user.getage ()); }    }}

Output results

ab 20a 30
Comparison between-comparable and comparator

Comparable forcibly sorts the objects that implement each of its classes. This sort is called the natural ordering of the class, and the CompareTo method of the class is called its natural comparison method. The list of objects (and arrays) that implement this interface can be automatically sorted by Collections.sort (and Arrays.sort). An object that implements this interface can be used as a key in an ordered map or an element in an ordered collection without specifying a comparer.

Comparator force a comparison function that collection a whole sort of an object. You can pass Comparator to the sort method, such as Collections.sort or arrays.sort, allowing for precise control over the sort order. You can also use Comparator to control the order of certain data structures, such as ordered set or ordered mappings, or to provide sorting for objects that do not have a natural order collection. Thought is actually---in Java design patterns. -Strategist Mode

Summary: The two methods have advantages and disadvantages, with comparable simple, as long as the realization of comparable interface object directly become a comparable object, but need to modify the source code, with the advantage of comparator is 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 are 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 can save a lot of duplication of work.

Comparable and comparator 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.