Comparable and comparator

Source: Internet
Author: User

Reproduced

the difference between comparable and comparator (reprint)
Comparable &Comparator are used to implement the comparison and ordering of the elements in the collection, except that comparable is the sort of method implementation defined within the collection, Comparator is the sort implemented outside the collection, so if you want to implement sorting, you need to define it outside the collection. Methods of Comparator interfaces or methods that implement comparable interfaces within a collection. Comparator is located under Package Java.util, and comparable is located under package Java.lang comparable is an interface that the object itself has implemented to support 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, in the sort method of collections class, if you do not specify comparator, then it is sorted in natural order, As the API says: Sorts the specified list into ascending order, according to the natural ordering of its elements. All elementsinchThe list must implement the comparableInterfacethe natural order here is to implement the sorting method of the comparable interface settings.  While Comparator is a dedicated comparator, you can write a comparator to compare the size of two objects when the object does not support self-comparison or the self-comparison function does not meet your requirements. It can be said that one is self-completed comparison, one is the difference between the external program implementation comparison. Using Comparator is the strategy mode (strategy design pattern), which does not change the object itself, but uses a policy object (strategyObject) 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. //Abscomparator.javaImport java.util.*; Public   classAbscomparator implements Comparator { Public   intCompare (Object O1, Object O2) {intV1 =Math.Abs ((Integer) O1). Intvalue ()); intV2 =Math.Abs ((Integer) O2). Intvalue ()); returnV1 > V2?1: (V1 = = v2?)0:   -1); You can test Abscomparator with the following class://Test.javaImport java.util.*;  Public   classTest { Public   Static   voidMain (string[] args) {//generates an array of 20 random integers (with positive negative)Random rnd =NewRandom (); integer[] Integers=Newinteger[ -];  for(inti =0;   i < integers.length; i++) Integers[i]=NewInteger (Rnd.nextint ( -) * (Rnd.nextboolean ()?1:   -1)); System. out. println ("sort using integer built-in methods:");           Arrays.sort (integers); 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, namelyintCompare (t O1, T O2) and Boolean equals (Object obj) to compare two comparator for equalitytrueOnlyifThe specifiedObject  isAlso a comparator and it imposes the same ordering as  ThisComparator. 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 onlyintCompareTo (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 the size of Person1 and an existing person object Person2, and I can call it this way: Person1.comparto (Person2), which can be judged by the return value, and at this point if you define a Personcomparator (implements the comparator interface), then you can: Personcomparator comparator=Newpersoncomparator (); Comparator.compare (Person1,person2);. 

Comparable and comparator

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.