Comparison of Java comparator comparable interface and Comaprator interface

Source: Internet
Author: User
Tags comparable java comparator

Comparable interface: Let custom objects have a comparison rule

Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Comparator;/** Comparable interface: Allow custom objects to have comparison rules * **/ Public classComparabledemo { Public Static voidMain (string[] args) {ArrayList<Student> list =NewArraylist<student>(); List.add (NewStudent ("Zhangsan", 18)); List.add (NewStudent ("Zhangsan", 28)); List.add (NewStudent ("Lisi", 20)); List.add (NewStudent ("Wangwu", 20)); List.add (NewStudent ("Xiaoming", 21)); List.add (NewStudent ("Dahuang", 22)); //all elements in the list must implement the comparable interfaceCollections.sort (list,NewComparator<student>() {@Override Public intCompare (Student O1, Student O2) {//O1 and O2 comparison: Ascending//Ascending by name, if name is equal and then age-based ascending//return O1.getname (). Equals (O2.getname ())? O1.getage ()-//o2.getage ()//: O1.getname (). CompareTo (O2.getname ()); //O2 and O1 comparison: Descending//in descending order of age, if the age is equal and the name is the main descending                returnO2.getage () = = O1.getage ()?o2.getname (). CompareTo (O1.getname ()): O2.getage ()-O1.getage (); }        });//I use comparator to make student have a comparative rule         for(Student s:list) {System.out.println (s); }    }}
 Packagecn.edu360; Public classPerson {PrivateString name; Private intAge ; Private Charsex;  PublicPerson () {Super(); }     PublicPerson (String name,intAgeCharsex) {         This. Name =name;  This. Age =Age ;  This. Sex =sex; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     Public CharGetsex () {returnsex; }     Public voidSetsex (Charsex) {         This. Sex =sex; } @Override PublicString toString () {return"Person [name=" + name + ", age=" + Age + ", sex=" + Sex + "]"; }}

Output Result:

  

Student [Name=zhangsan, age=28]

  Student [Name=dahuang, age=22]

Student [Name=xiaoming, age=21]
Student [Name=wangwu, age=20]
Student [Name=lisi, age=20]
Student [Name=zhangsan, age=18]

Comparator Comparison interface:
Overriding the existing comparison rules for an element object
To have a comparison rule for objects that do not have a comparison rule

  

Importjava.util.ArrayList;Importjava.util.Collections;ImportJava.util.Comparator;/** Comparator Comparison interface: * Overwrite the existing comparison rules of the element object * Let the object with no comparison rule have a comparison rule **/ Public classComparatordemo { Public Static voidMain (string[] args) {ArrayList<Integer> list =NewArraylist<integer>(); List.add (10); List.add (0); List.add (20); List.add (-19); List.add (19); List.add (100); SYSTEM.OUT.PRINTLN (list);//[Ten, 0, -19 , +, +]//anonymous inner class essentially an anonymous subclass object that inherits a class or implements an interfaceComparator C =NewComparator<integer>() {@Override Public intCompare (integer O1, integer o2) {//O1 and O2 comparison: Ascending//return O1.compareto (O2); //return o1-o2;//for integer type values, the CompareTo method is the same as the effect of using subtraction directly .//O2 and O1 comparison: Descending//return O2.compareto (O1);                returnO2-o1;//for integer type values, the CompareTo method is the same as the effect of using subtraction directly .            }        }; //Public static <T> void sort (list<t> List, comparator<? super t> C)//sorts the specified list according to the order produced by the specified comparerCollections.sort (list, c); SYSTEM.OUT.PRINTLN (list);//[+, 0, -19]        intLocation = Collections.binarysearch (list, 0, C);//If you want to find the collection in descending order, you need to use the comparatorSystem.out.println (location); }}

Output Result:

  

[10, 0, 20,-19, 19, 100]
[100, 20, 19, 10, 0,-19]
4

Summarize:

The difference between comparable and comparator

Both comparable and comparator are used to implement the comparison and ordering of elements in the collection.
Comparable is a sort of method implementation defined within the collection, located under Java.util.
Comparator is the sort implemented outside the collection, located under Java.lang.

Comparable is an object itself has been supported by the implementation of self-comparison interface, such as String, Integer itself implemented the comparable interface, you can complete the comparison size operation. Custom classes can be sorted after being added to the list container, or the comparable interface may be implemented, and if comparator is not specified in the sort method of the collections class, it is sorted in a natural order. The so-called natural order is the implementation of the comparable interface settings of the ordering mode.


Comparator is a dedicated comparator that can write a comparator to achieve the size comparison between two objects when the object does not support self-comparison or the self-comparison function does not meet the requirements. Comparator embodies a strategy pattern (strategy design pattern) that does not change the object itself, but instead uses a policy object (strategy object) to change its behavior.

All in all comparable is a self-completed comparison, comparator is an external program implementation comparison.

Comparison of Java comparator comparable interface and Comaprator 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.