What is Comparable interface
Answer: Below are details:
- Comparable is an interface which compares this object with specified object which will be supplied at run time for ordering.
- In another words it compares itself with others with same type of object
- Any class whose comparison will be performed itself should implements Comparable interface in order compare with its instances
- It return zero, negative integer or a positive integer when this object is equal to, less than or greater than the specified object supplied at run time.
- When class implements Comparable interface it must override public int compareTo(T o) method in order to compare object
Please see below example ComparableTest where class itself compare with another object created in same class for both descending and ascending order:
package com.javahonk.algorithms; import java.util.Arrays; public class ComparableTest implements Comparable<ComparableTest> { static Boolean ascending = false; String fruitName; public String getFruitName() { return fruitName; } public void setFruitName(String fruitName) { this.fruitName = fruitName; } ComparableTest(String fruitName) { this.fruitName = fruitName; } public static void main(String[] args) { ComparableTest[] comparableTests = new ComparableTest[3]; comparableTests[0] = new ComparableTest("Mango"); comparableTests[1] = new ComparableTest("Apple"); comparableTests[2] = new ComparableTest("Cherry"); // Sort in descending order System.out.println("Sort in descending order"); Arrays.sort(comparableTests); for (ComparableTest comparableTest : comparableTests) { System.out.println(comparableTest.getFruitName()); } // Sort in ascending order System.out.println("\nSort in ascending order"); ComparableTest.ascending = true; Arrays.sort(comparableTests); for (ComparableTest comparableTest : comparableTests) { System.out.println(comparableTest.getFruitName()); } } @Override public int compareTo(ComparableTest o) { if (ascending) { return this.getFruitName().compareTo(o.getFruitName()); }else { return o.getFruitName().compareTo(this.getFruitName()); } } }
Output: