Java-Comparable and Comparator with example
Comparable Interface and Comparator Interface in java are very useful for sorting the collection of objects The Comparable Interface in Java with Example The Comparable interface has the compareTo (T obj) method which is used by sorting methods, you can check any Wrapper, String, or Date class to confirm this. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as an argument. Comparable is present in java.lang package. We can sort the list elements of Comparable type by Collections.sort(List) method. Example: Consider an Employee class that has members like, username,userid, year of joining. Suppose we wish to sort a list of Employees based on the year of joining. We can implement the Comparable interface with the Employee class, and we override the method compareTo() of Comparable interface. Employee.java //A Java program to demonstrate the u