Monday 24 January 2022

Comparable and Comparator Interface

 Comparable interface is used to sort or order the elements on the basis of single field. Using this we can only sort using single field. Comparable interface is present in java.lang.comparable package.

package java.lang;

public interface Comparable<T> {
int compareTo(T var1);
}

Comparator interface is used to sort or order the elements on the basis of multiple fields. Using this we can create different comparator and sort elements on the basis of different fields. Comparator interface is present in java.util package.

package java.util;

import java.io.Serializable;
import java.util.Comparators.NaturalOrderComparator;
import java.util.Comparators.NullComparator;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import java.util.function.ToIntFunction;
import java.util.function.ToLongFunction;

@FunctionalInterface
public interface Comparator<T> {
int compare(T var1, T var2);

boolean equals(Object var1);

Observe that Comparator is marked functional interface . It may be because all classes which implement Comparator interface  by default will have equals implementation from default super class (Object).

No comments:

Post a Comment