Understanding Comparable Interface
Explore how Java's Comparable interface allows sorting of list elements using the compareTo method. Understand its role in sorting built-in types and how to implement it in custom classes for effective data ordering.
We'll cover the following...
Comparable introduction
Collections.sort() method sorts the given List in ascending order. But the question is, how does the sort() method decide which element is smaller and which one is larger?
Each wrapper class(Integer, Double, or Long), String class, and Date class implements an interface called Comparable. This interface contains a compareTo(T o) method which is used by sorting methods to sort the Collection. This method 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 ...