Search code examples
javasortingcollectionscomparable

Is it possible to have TWO compareTo methods for a value class?


Quick example is a collection of users' first and last name.

One method requires that I compare using the first name, another using the last name. Is it possible to have two different compareTo()?

Or am I just better off creating two different value classes?


Solution

  • Using compareTo means that you are using the Comparable interface, which defines only one "natural order" for your class.

    To have any other ordering, it's best to create a separate class that implements Comparator for each ordering you need. You don't need to create a different value class.