The difference between comparable and comparator in Java

The difference between comparable and comparator in Java

brief introduction

java. Lang. comparable and Java util. Comparator is two easily confused interfaces. Both of them have the meaning of comparison. What are the differences between the two interfaces and under what circumstances?

Comparable

Comparable is Java The interface under the Lang package can be regarded as the basic language interface of Java.

In fact, the comparable interface defines only one method:

 public int compareTo(T o);

All classes implementing this interface need to implement the CompareTo method to represent the comparison between the two classes.

The order after comparison and sorting is called natural ordering according to Java. This order is used for some sortable sets, such as sortedset, SortedMap, etc.

When these sortable collections are used to add corresponding objects, the CompareTo method will be called to sort the natural ordering.

Almost all digital type objects: integer, long, double, etc. implement this comparable interface.

Comparator

Comparator is a functional interface, which needs to implement the compare method:

int compare(T o1,T o2);

Comparator in Java Util package represents a tool class used to assist sorting.

When talking about comparable, we mentioned that comparable specifies the natural ordering of objects. If we want to sort according to our custom method when adding to the sortable collection class, we need to use the comparator at this time.

Collections. sort(List,Comparator),Arrays. Sort (object [], comparator) and other auxiliary method classes can define sorting rules by passing in a comparator.

In the sorting process, first check whether the comparator exists. If it does not exist, the default natural ordering will be used.

Another difference is that comparator allows the comparison of null parameters, while comparable does not, otherwise it will crawl out of NullPointerException.

for instance

Finally, we give an example of natural ordering and comparator:

    @Test
    public void useCompare(){
        List<Integer> list1 = Arrays.asList(5,3,2,4,1);
        Collections.sort(list1);
        log.info("{}",list1);

        List<Integer> list2 = Arrays.asList(5,1);
        Collections.sort(list2,(a,b) -> b - a);
        log.info("{}",list2);
    }

Output results:

[main] INFO com.flydean.CompareUsage - [1,5]
[main] INFO com.flydean.CompareUsage - [5,1]

By default, integers are arranged in ascending order, but we can change this process by passing in a comparator.

Examples of this article https://github.com/ddean2009/learn-java-collections

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