collections
beginnerComparable vs Comparator
Define an object's natural order once (Comparable) or supply an alternate ordering on demand (Comparator).
Sorting in Java rests on two interfaces that answer the same question — "which of these two comes first?" — but from different places. Comparable defines an object's single natural ordering from inside the class, while Comparator defines an external, alternate ordering supplied at the point of sorting. Knowing which to use, and when, is a staple interview topic precisely because the distinction is about ownership of the ordering.
Comparable is your default ranking on a leaderboard. Comparator is "sort the same list by name instead" for a different view.
Key Concepts
1
A class implements Comparable by providing compareTo(other), baking in one canonical order — String sorts alphabetically, Integer numerically. This is the order used by Collections.sort(list) and TreeMap/TreeSet when no comparator is given. A Comparator is a separate object implementing compare(a, b), passed explicitly to sort or a tree structure. You reach for it when you need an order the class did not define, when you need several different orders (by name, then by age), or when you cannot modify the class at all. Since Java 8, comparators are pleasant to build with Comparator.comparing(User::getName).thenComparing(User::getAge).reversed() rather than hand-written comparison logic.
ComparablecompareTo(other)StringIntegerCollections.sort(list)
2
All three methods return a negative number, zero, or a positive number for less-than, equal, and greater-than. The classic bug is implementing this with subtraction like a.id - b.id, which overflows for large or negative ints and silently produces wrong orderings; use Integer.compare(a, b) instead. A subtler contract issue: for TreeSet and TreeMap, ordering defines equality, so a comparator that returns 0 for two "different" objects will treat them as duplicates — keep your comparison consistent with equals to avoid surprises.
a.id - b.idInteger.compare(a, b)TreeSetTreeMapequals