Comparable versus Comparator in Java

Introduction to the

Java.lang.Com parable and java.util.Comparator are two interfaces that can be easily confused. What are the differences between the two interfaces and when can they be used?

Comparable

Comparable is the interface underneath the Java.lang package, which can be considered the base language interface for Java.

In fact, the Comparable interface defines only one method:

 public int compareTo(T o);
Copy the code

Any class that implements this interface needs to implement the compareTo method, which represents a comparison between two classes.

This order is called a Natural ordering in Java. This order is used in sortedsets such as sortedSets, sortedMaps, etc.

When an object is added using the orderable set, the compareTo method is called to order the natural ordering.

Almost all numeric objects: Integer, Long, Double, and so on implement this Comparable interface.

Comparator

The Comparator is a FunctionalInterface that implements the compare method:

int compare(T o1, T o2);
Copy the code

The Comparator in the java.util package means that it is a utility class for sorting.

Comparable specifies the natural ordering of objects. We use the Comparator if we want to order a collable set in a way that we have defined for ourselves.

Collections.sort(List,Comparator), arrays.sort (Object[],Comparator) and other auxiliary method classes can customize collation rules by passing in a Comparator.

When ordering, the Comparator is checked to see if it exists. If it does not, the default natural ordering is used.

Another difference is that the Comparator allows comparisons of null parameters, whereas Comparable is not allowed, otherwise a NullPointerException will crawl out.

For example

Finally, here’s an example of natural ordering and Comparator:

    @Test
    public void useCompare(a){
        List<Integer> list1 = Arrays.asList(5.3.2.4.1);
        Collections.sort(list1);
        log.info("{}",list1);

        List<Integer> list2 = Arrays.asList(5.3.2.4.1);
        Collections.sort(list2, (a, b) -> b - a);
        log.info("{}",list2);
    }
Copy the code

Output result:

[main] INFO com.flydean.CompareUsage - [1.2.3.4.5]
[main] INFO com.flydean.CompareUsage - [5.4.3.2.1]
Copy the code

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

Examples of this article github.com/ddean2009/l…

Welcome to pay attention to my public number: procedures those things, more wonderful waiting for you! For more, visit www.flydean.com