Java lang (comparable interface) and Java util (comparator interface) analysis comparison

Source: Internet
Author: User
Tags comparable java util

The comparable interface forces the overall ordering of objects that implement each of its classes. -Natural sort. The CompareTo of a class is called a natural comparison method. Public interface Comparable<t> {public    int compareTo (T o);}

This interface forces the overall ordering of the objects for each class that implements it. This sort is called the natural ordering of the class, and the CompareTo method of the class is called its natural comparison method .

The list of objects (and arrays) that implement this interface can be automatically sorted by Collections.sort (and Arrays.sort). An object that implements this interface can be used as an element in a key or an ordered set (interface java.util.sortedset<e>) in an ordered map (interface java.util.sortedmap<k,v>) without specifying a comparer (interface java.util.comparator<t>).

There are three conditions for the return value of the CompareTo method:

    1. E1.compareto (E2) > 0 E1 > E2
    2. E1.compareto (e2) = 0 = E1 = E2
    3. E1.compareto (E2) < 0 E1 < E2

Attention:

1. Since null is not a class and is not an object, you should be aware of e.compareto (null) When overriding the CompareTo method, even if e.equals (null) returns False,compareto The method should also actively throw a null pointer to the exception nullpointerexception.

The 2.Comparable implementation class overrides the CompareTo method generally requires that the results of e1.compareto (e2) = = 0 be consistent with E1.equals (E2). In this way, the collection containers that are sorted by the natural sort of the class, such as SortedSet, can be used to ensure that the order of the saved data is consistent with the imagination.

Examples of interface implementations:

Import Java.util.arraylist;import Java.util.collections;public class Car implements Comparable<object>{public string Name;public int price;public Car (string name, int price) {this.name = Name;this.price = Price;} Public String toString () {return this.name + ":" + This.price;} @Overridepublic int compareTo (Object o) {if (o instanceof car) {car  car = (Car) o;int Result;result = This.price-car . price;//when the price of car compares its name, sort the IF (result = = 0) by the Comparato () method of the string {result = This.name.compareTo (car.name);} return result;} return 0;} public static void Main (string[] args) {arraylist<car> all = new Arraylist<car> () All.add (New Car ("Lamborghini", 400 ); All.add (new Car ("BMW"), All.add ("Mercedes"), All.add (New car ("Ferrari", 300)); System.out.println (All); Collections.sort (All); System.out.println (All);}}

Print out:

[Lamborghini: 400, BMW: 100, Mercedes: 95, Ferrari: 300]
[Mercedes: 95, BMW: 100, Ferrari: 300, Lamborghini: 400]

Comparator Comparator Interface (policy design mode)

If we need to control the order of a class, and the class itself does not support ordering (that is, it does not implement the comparable interface), then you can set up a comparer for that class to sort by simply implementing the comparator interface.

Public interface comparator<t> {     int compare (t O1, T O2);     Boolean equals (Object obj);}

There are three main ways of using it:

1. Create an implementation class for the Comparator interface and assign a value to an object to write the collation for the custom class in the Compare method

2. Passing a Comparator object as a parameter to a method of the Sort class

3. Add the custom class used in the Compare method to the Sort class

Examples of interface operations:

Import Java.util.arraylist;import Java.util.collections;import Java.util.comparator;public class Car {public String name;public int price;public Car (String name, int price) {this.name = Name;this.price = Price;} Public String toString () {return this.name + ":" + This.price;} public static void Main (string[] args) {arraylist<car> all = new Arraylist<car> () All.add (New Car ("Lamborghini", 400 ); All.add (new Car ("BMW"), All.add ("Mercedes"), All.add (New car ("Ferrari", 300)); System.out.println (All); Collections.sort (All, New Mycomparator ()); System.out.println (All);}} Class Mycomparator implements comparator<car> {@Overridepublic int compare (car O1, car O2) {//TODO auto-generated m Ethod stubint result = o1.price-o2.price;if (Result! = 0) {return result;} else {return o1.name.compareTo (o2.name);}}}

Print out:

[Lamborghini: 400, BMW: 100, Mercedes: 95, Ferrari: 300]
[Mercedes: 95, BMW: 100, Ferrari: 300, Lamborghini: 400]

comparison of comparable and comparator

Comparable is a sort interface, and if a class implements the comparable interface, it means "this class supports sorting."
And Comparator is a comparator; if we need to control the order of a class, we can create a "comparer for that class" to sort by.

The former should be fixed, bound to a specific class, and the latter more flexible, which can be used for each class that needs to compare functions. It can be said that the former belongs to "static binding", while the latter can be "dynamically bound".

It is easy to see that comparable is equivalent to an "internal comparator", while Comparator is equivalent to an "external comparator".

Java lang (comparable interface) and Java util (comparator interface) analysis comparison

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.