Comparable Interface
Learn Comparable Interface (Comparable & Comparator, Collection Framework) with worked examples, diagrams and interview questions. Free on JavaSchoolLab.
What is Comparable? Comparable gives a class its natural order : the one default way two objects of that class are compared. It has a single method, compareTo . Once a class implements it, Collections.sort , Arrays.sort , TreeSet , TreeMap , PriorityQueue and stream().sorted() all know how to order it. Package java.lang (no import needed). The interface is Comparable<T> . One method: int compareTo(T other) , implemented inside the class being sorted. Return negative if this object comes first, zero if equal in order, positive if this comes later. String , Integer , Long , Double , Character ,...