Java Comparable Interface
We implement comparable interface when we need a new logic for determining equality. if two objects are equal, the equals() method returns true and compareTo() method returns 0. The basic need for checking equality is for sorting our collection in our specific requirement.
We need to implement a consistency with equals() and compareTo() method in our collection object, if not, all the collection classes behavior towards this object may become unpredictable. Our collection object will be consistent if and only if x.equals(y) is true whenever x.compareTo(y) equals 0.
The Comparable interface has only one method.
It looks like below:
public interface Comparable<T> { public int compareTo(T o); }
Example Comparable:
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Country implements Comparable<Country> { private String name; public Country(String name) { this.name = name; } public String toString() { return name; } public int compareTo(Country d) { return name.compareTo(d.name); // Returns natural ordering of the Alphabets. } public static void main(String[] args) { List<Country> c = new ArrayList<>(); c.add(new Country("INDIA")); c.add(new Country("CHINA")); Collections.sort(c);// sort by name System.out.println(c);// [CHINA, INDIA] } }
Output:
[CHINA, INDIA]
The implementation of the comparable interface for string class is already defined, so it is comparable by default.