Comparison between java Comparable interface and Comparator Interface

Source: Internet
Author: User

Comparison of the two interfaces:
1: Comparable is the sorting of methods defined inside the set, and Comparator is the sorting implemented outside the set. The Comparable interface is really convenient for processing natural sorting, but there are also some shortcomings. First, all the elements in the input array or list must be Comparable. Interfaces only implement natural sorting. If there are other requirements, such as reverse order or other specific order, they cannot adapt to the changes. A typical case is that there is a collection class that requires sorting based on different requirements. It is not enough for the Comparable interface alone.
2: If a class implements the Camparable interface, it indicates that the objects of this class can be compared with each other. A set composed of these class objects can be directly sorted using the sort method. Generally, all the beans we write need to implement this interface, which is also the Standard javabean specification.
3: Comparator can be seen as an algorithm implementation that separates algorithms from data. Comparator can also be used in the following two environments:
1. Category designers do not consider comparison issues and do not implement Comparable. You can use Comparator to sort objects without changing the object itself.

2. Multiple sorting criteria can be used, such as ascending or descending.


Use the Comparator interface for sorting: The compare method is implemented. The return value is a negative integer, zero, or positive integer based on whether the first parameter is smaller than, equal to, or greater than the second parameter.
A comparison function that forcibly sorts the collection objects. Comparator can be passed to the sort method (such as Collections. sort or Arrays. sort) to allow precise control over the sorting order. You can also use Comparator to control the order of certain data structures (such as ordered set or ordered ing), or provide sorting for object collections without natural order.

Implement the Comparator Interface

import java.util.*;public class AbsComparator implements Comparator {public int compare(Object o1, Object o2) {int v1 = Math.abs(((Integer) o1).intValue());int v2 = Math.abs(((Integer) o2).intValue());return v1 > v2 ? 1 : (v1 == v2 ? 0 : -1);}}

Use AbsComparator to sort the set:

Import java. util. *; public class Test {public static void main (String [] args) {// generate an array of 20 Random integers (with positive and negative values) Random rnd = new Random (); integer [] integers = new Integer [20]; for (int I = 0; I <integers. length; I ++) integers [I] = new Integer (rnd. nextInt (100) * (rnd. nextBoolean ()? 1:-1); System. out. println ("sort by Integer built-in method:"); Arrays. sort (integers); System. out. println (Arrays. asList (integers); System. out. println ("sorted by AbsComparator:"); Arrays. sort (integers, new AbsComparator (); System. out. println (Arrays. asList (integers ));}}

Use the Comparable interface to complete sorting: The list of objects (and Arrays) that implement this interface can be automatically sorted by Collections. sort (and Arrays. sort. The object implementing this interface can be used as a key or element in an ordered set in an ordered ing without specifying a comparator.

Import java. util. arrayList; import java. util. collections; import java. util. list; public class UserPo implements Comparable {private String name; private int age; public UserPo (String name, int age) {this. name = name; this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}@ Overridepublic int compareTo (Object o) {return this. age-(UserPo) o ). getAge ();} public static void main (String args []) {List
 
  
Array = new ArrayList
  
   
(); UserPo u1 = new UserPo ("Zhang San", 30); UserPo u2 = new UserPo ("Li Si", 28); UserPo u3 = new UserPo ("Wang Wu ", 26); array. add (u1); array. add (u2); array. add (u3); Collections. sort (array); for (UserPo p: array) {System. out. println (p. getName () + ":" + p. getAge ());}}}
  
 


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.