Java comparable interface and comparator interface

Source: Internet
Author: User

Comparable & Comparator are used to implement the comparison and sorting of elements in the set;

Comparable is the sort of method implementation defined within the set;

Comparator is the sort implemented outside the set;

Therefore, if you want to implement a sort, you need to define the method of the Comparator interface outside the collection or implement the comparable interface within the collection.

Comparator is located under Package Java.util, while comparable is under package Java.lang

Comparable is an interface that the object itself has already supported for self-comparison (such as String, Integer itself can do the comparison size operation, has implemented the comparable interface)

Custom classes to be able to sort after joining the list container, you can implement the comparable interface, when sorted by the sort method of the collections class, if you do not specify comparator, then in a natural order, as the API says:
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the comparable interface
The natural order here is to implement the sorting method of the comparable interface settings.

Comparator is a dedicated comparator, and when the object does not support self-comparison or the self-comparison function does not meet your requirements, you can write a comparator to achieve a comparison of the size between the two objects.

It can be said that one is self-completed comparison, one is the difference between the external program implementation comparison.

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.

1 //Abscomparator.java2 ImportJava.util.*;3 classAbscomparatorImplementsComparator {4      Public intCompare (Object O1, Object O2) {5         intV1 =Math.Abs ((Integer) O1). Intvalue ());6         intV2 =Math.Abs ((Integer) O2). Intvalue ());7         returnV1 > V2? 1: (V1 = = v2? 0:1);8     }9}
1 //Test.java2 ImportJava.util.*; 3 4  Public   classTest {5      Public   Static   voidMain (string[] args) {6     7       //generates an array of 20 random integers (with positive negative)8Random rnd =NewRandom (); 9integer[] integers =NewInteger[20]; Ten        for(inti = 0;   i < integers.length; i++)      OneIntegers[i] =NewInteger (rnd.nextint) * (Rnd.nextboolean ()? 1:-1));  A      -System.out.println ("Sort by integer built-in method:");  - arrays.sort (integers);  the System.out.println (arrays.aslist (integers));  -      -System.out.println ("Sort by abscomparator:");  -Arrays.sort (Integers,Newabscomparator ());  + System.out.println (arrays.aslist (integers));  -     }      +}

Collections.sort (list<t> list, comparator< Super t> C) is used to sort the list.

If you are not calling the sort method, compare the size of the two objects directly, as follows:
Comparator defines two methods, namely int compare (T O1, T O2) and Boolean equals (Object obj),
Used to compare whether two comparator are equal
True if the specified object is also a comparator and it imposes the same ordering as this comparator.
Sometimes when implementing the comparator interface, the Equals method is not implemented, and the program does not have an error because the class that implements the interface is also a subclass of the object class, and the object class has implemented the Equals method

The comparable interface provides only the int compareTo (T O) method, which means that if I define a person class that implements the comparable interface, then when I instantiate the person1 of the person class, I want to compare person1 and   The size of an existing person object Person2, I can call it this way: Person1.comparto (Person2), can be judged by the return value, and at this point if you define a Personcomparator (implements the comparator interface), then you can do this: Personcomparator comparator= new Personcomparator ();
Comparator.compare (Person1,person2);.

Java comparable interface and 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.