Difference between comaparable interface and comparator Interface

Source: Internet
Author: User

From: http://www.open-china.net/blog/7707.html

A class is provided, which requires writing a sectionCodeTo sort the following types of data (sort by index in descending order ):
Public Class {
Public int index;
Public String STR;
Public ...... ;
}
Condition:
1. A large amount of data is required;
2. good scalability: by other data types (such as string STR ,......) When sorting, you do not need to modify components, and other types of data may be added in the future.
(Tip: You can call the sorting in the ready-made java. util package .)

Differences between comparator and comparable interfaces for object sorting:

1. Comparable is a common interface. You can implement it to complete your own specific comparison. comparator can be seen asAlgorithmTo specify the comparator when the collection of containers needs to be compared. This shows a design mode (Strategy Mode strategy) To separate algorithms from data, just like function objects in C ++ STL.
2. The former should be relatively fixed and bound to a specific class, while the latter is flexible and can be used by various classes that require comparative functions. It can be said that the former belongs to "static binding", while the latter can "dynamic binding ".
3. The camparable interface of a class indicates that the objects of the class can be compared with each other. If described in mathematical language, there is a full order in the collection composed of objects of this class. In this way, the collection composed of this class object can be sorted using the sort method.
4. comparator has two functions:
A. If the class designer does not consider the Compare problem and does not implement the comparable interface, you can use comparator to implement comparison algorithms for sorting.
B,More flexible sorting rulesTo use different sorting criteria, such as ascending or descending, or to sort by other fields of the class in the future

Name class to implement the comparable interface to sort objects: 

Public class name implements comparable <Name> {Public String firstname, lastname, ID; public name (string firstname, string lastname, string ID) {This. firstname = firstname; this. lastname = lastname; this. id = ID;} public int compareto (name o) {// rewrite int lastcmp = lastname. compareto (O. lastname); Return (lastcmp! = 0? Lastcmp: firstname. compareto (O. firstname);} Public String tostring () {// easy output test return firstname + "" + lastname ;}}

Namesort class, test 

Import Java. util. *; public class namesort {public static void main (string [] ARGs) {// todo auto-generated method stub name [] namearray = new name [] {new name ("John", "Lennon", "3556465464644343 "), new name ("Karl", "Marx", "3556465461111111"), new name ("Groucho", "Marx", "3805236412578"), new name ("Oscar ", "grouch", "8854321622238")}; arrays. sort (namearray); For (INT I = 0; I <namearray. length; I ++) {system. out. println (namearray [I]. tostring ());}}}

The more flexible method is to implement the comparator interface., Use collections. Sort (list <t> list, comparator <? Super T> C) This method is sorted: 
First_name_order class

Import Java. util. *; public class first_name_order implements comparator <Name> {public int compare (name N1, name N2) {int firstcmp = n1.firstname. compareto (n2.firstname); Return (firstcmp! = 0? Firstcmp: n1.lastname. compareto (n2.firstname ));}}

In the above namesort, replace arrays. Sort (namearray); with the following statement:

 
List <Name> List = arrays. aslist (namearray); // convert the name array to listcollections. Sort (list, new first_name_order ());

Summary:
1. here, you can customize first_name_order through collections. sort (list, comparator) is used to sort data. When the demand changes and needs to be sorted by other rules (such as IDS), only one comaprator ---- id_order_comparator can be redefined, instead of modifying the name or the original sequencer first_name_order, and then modifying the client code, onlyProgramAn important principle of design-the open and closed principle, that is, new functions can be easily expanded by adding new classes to meet new requirements without modifying the original code.
2. if we use name to implement the comaparable interface, we must modify the comareto (Object O) method in name when we want to adopt a new sorting rule. This violates the open and closed principle, therefore, comparator should be used instead of comparable.
 

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.