Define natural and custom ordering for objects in collections.
When working with sorted collections like `TreeSet` or when using utility methods like `Collections.sort()` or `Arrays.sort()`, Java needs to know how to compare the objects to determine their order. There are two primary ways to define this comparison logic: the `Comparable` interface and the `Comparator` interface. The `Comparable` interface is used to define the 'natural ordering' of a class. To use it, a class must implement `Comparable` and override its single method, `compareTo(Object obj)`. This method compares the current object (`this`) with the specified object (`obj`) and returns a negative integer, zero, or a positive integer if `this` object is less than, equal to, or greater than the specified object, respectively. For example, the `String` and `Integer` classes both implement `Comparable`, defining their natural alphabetical and numerical orders. The limitation of `Comparable` is that it provides only one way to sort objects, and you must be able to modify the class's source code to implement it. The `Comparator` interface provides a way to define custom or alternative orderings. It is useful when you cannot modify the class's source code or when you need to sort objects in multiple different ways (e.g., sorting a list of `Person` objects by name, then by age). To use it, you create a separate class that implements the `Comparator` interface and overrides its `compare(Object obj1, Object obj2)` method. An instance of this comparator class can then be passed to the sort method. In summary: use `Comparable` for the single, natural ordering of a class, and use `Comparator` for all other sorting requirements.