
Comparable and Comparator
Comparable Interface Comparable Interface is meant for default natural Sorting order . It is present in Java.lang package . 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’s compareTo(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 and equals() . Compare()method is responsible to so
Continue reading on Dev.to React
Opens in a new tab




