Detailed explanation and difference between Java comparable and comparator

Detailed explanation and difference between Java comparable and comparator

Java provides us with two comparison mechanisms: comparable and comparator. What is the difference between them? Let's learn about it today.

Comparable natural sorting

Comparable in Java Lang package is an interface with only one method CompareTo ():

Comparable allows the objects of the classes that implement it to be compared. The specific comparison rules are based on the rules in the CompareTo method. This order is called natural order.

The return value of CompareTo method has three conditions:

Note: @ h_ 404_ 30@

1. Since null is neither a class nor an object, you should pay attention to e.compareto (null) when rewriting the CompareTo method. Even if e.equals (null) returns false, the CompareTo method should actively throw a null pointer exception NullPointerException.

2. General requirements for rewriting CompareTo method by comparable implementation class E1 CompareTo (E2) = = 0 and E1 Equals (E2) is consistent. In this way, when using sortedset and other collection containers sorted according to the natural sorting of classes in the future, the order of saved data can be guaranteed to be consistent with the imagination. One may wonder what happens if the second point above is violated?

For example, if you add two objects a and B to a sortedset successively, a and B satisfy (! A.equals (b) & & a.compareto (b) = = 0) and do not specify another comparator, when you add a and then add B, the addition failure will return false, and the size of the sortedset will not increase, because they are the same in the sortedset, The sortedset cannot be duplicated.

In fact, the results of all Java core classes that implement the comparable interface are consistent with the equlas method. Collections can be used for lists or arrays that implement the comparable interface Sort() or arrays Sort () method.

Only objects that implement the comparable interface can be directly used as the key of SortedMap (sortedset). Otherwise, the comparator collation must be specified outside.

Therefore, if a self-defined class wants to use an ordered collection class, it needs to implement the comparable interface, such as:

The above code also rewrites equlas(), hashcode() methods, which must be rewritten when custom classes want to compare.

When rewriting CompareTo later, it is necessary to judge the same attribute and compare the next attribute, and compare all attributes once.

The comparable interface is part of the Java collection framework.

Comparator custom sorting

Comparator in Java Util package is also an interface. Before JDK 1.8, there were only two methods:

Many methods have been added since JDK 1.8:

Basically, they are related to functions. The new ones in 1.8 will not be introduced here.

It can be seen from the above that using natural sorting requires the class to implement comparable and override the comparato method internally.

Comparator makes sorting rules externally and passes them to some classes as sorting policy parameters, such as collections sort(),Arrays. Sort (), or some internally ordered sets (such as sortedset, SortedMap, etc.).

The use method is mainly divided into three steps:

1. Create an implementation class of comparator interface and assign it to an object

Write a collation for a custom class in the compare method

2. Pass the comparator object as a parameter to a method of the sorting class

3. Add the custom class used in compare method to the sort class

for instance:

In fact, it can be seen that the use of comparator is a strategy mode. Students who are not familiar with the strategy mode can click here to view: strategy mode: the fixed routine of online novels.

The sorting class holds a reference to the comparator interface:

Comparator comparator; We can pass in comparator implementation classes of various custom sorting rules and formulate different sorting strategies for the same class.

summary

There are two sorting methods in Java:

Comparable natural sorting. (entity class implementation) comparator is a custom sort. (if the entity class cannot be modified, it can be created directly at the caller) @ h_404_30@

At the same time, comparator (custom sorting) rules are used for comparison.

For some common data types (such as string, integer, double...), they implement the comparable interface and the CompareTo method by default. We can use them directly.

For some custom classes, they may need to implement different comparison strategies in different situations. We can create a new comparator interface and use a specific comparator implementation for comparison.

This is the difference between comparable and comparator.

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>