Comparable Interface
Comparable Interface is meant for default natural Sorting order.
It is present in
Java.langpackage.it is Contains Only one method
Compare To().-
Compare To() method is responsible to sort the elements.
You define the natural ordering for your objects by implementing the
Comparable’scompareTo(T o)method in your custom objects. For example, if we want to compare the Person object based on the first name we’ll implement the Comparable interface .
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ComparatorExample {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("jai");
al.add("vijay");
al.add("maddy");
al.add("ajai");
al.add("don");
Collections.sort();
System.out.println(al);
}
}
Comparator Interface
Comparator Interface is meant for Customized Sorting Order.
It is present in
Java.util.It contains two method
Compare()method andequals().-
Compare()method is responsible to sort the elements.
If we want to define a total ordering on an object that has no natural ordering or if we want to override the natural ordering then we leverage the Comparator interface to do so. For example, if we want to override the natural ordering of
Personobjects and compare thePerson objectbased on the age we’ll implement the Comparator interface
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ComparatorExample implements Comparator <String>{
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("jai");
al.add("vijay");
al.add("maddy");
al.add("ajai");
al.add("don");
Collections.sort(al,new ComparatorExample());
System.out.println(al);
}
@Override
public int compare(String o2, String o1) {
return o2.compareTo(o1);
}
}
Top comments (0)