Implementation methods of several common comparators in Java

In Java, the sorting of object arrays is often involved, so it involves the comparison between objects.

Generally, the comparison between objects can be seen from two aspects:

The first aspect: whether the address of the object is the same, that is, whether it refers to the same object. This can be done directly with "= =".

The second aspect: compare from the perspective of an attribute of the object.

In terms of the latest jdk8, there are three methods to implement object comparison:

1、 Override the equals () method of the object class;

2、 Inherit the comparable interface and implement the CompareTo () method;

3、 Define a separate object comparator, which inherits from the comparator interface and implements the compare () method.

Due to the different sorting methods used, the specific method selected to realize object comparison will also be different.

Overriding the equals () method is generally used to sort the object array by yourself. When using the built-in sorting algorithm in Java, it is feasible to use the latter two methods.

Let's first look at the second method. This method is to let the class you write inherit the comparable interface and implement the CompareTo () method. In this case, use Java. Util. Arrays. Sort ()

Instead of specifying a specific comparator, the sort () method uses the object's own comparison function to sort the objects.

Here is a specific example:

Generally, we can meet the actual development problems by using the above two methods. However, the comparator interface is required when:

If you want to improve the object comparison function on the basis of the developed code without changing the previous code, in this case, start from jdk1 The comparator interface appeared after 8, which is a remedy for this situation.

In this case, we need to define an object comparator separately, inherit the comparator interface, and implement the compare() method. The example code is as follows:

In the above three cases, different methods are selected to solve practical problems due to different specific conditions.

This article discusses the implementation methods of several common comparators in Java, which is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

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
分享
二维码
< <上一篇
下一篇>>