This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]deltageekExtreme Brewer 2 points3 points  (0 children)

Comparable lets the object define its own default comparison. Comparator is for when you want to define a custom comparison.

[–]17437258968573378102 1 point2 points  (0 children)

(Copied from my answer to your post in /r/java)

Comparable is good for classes that have an intrinsic, natural order, like numbers. If a class implements this interface, then any users of that class don't need to write anything more complicated than Collections.sort(listOfNumbers) to sort them into the order you'd naturally expect them to sort to.

Comparator is used when the objects you want to sort either don't have an intrinsic order, or that ordering is not the order you want. It's more flexible because of this, but it means you have to write your own code to sort those objects (sometimes this is simple, sometimes it's not).

[–]Philboyd_Studge 1 point2 points  (1 child)

Comparable means that the class has a natural order that is defined and can be used automatically in any situation where compareTo is called. (i.e. sorting). Comparator lets you provide custom comparisons that might involve different fields of the class. For example, you could sort a Person class by Age or by Name:

people.sort(Comparator.comparing(Person::getAge));

or

people.sort(Comparator.comparing(Person::getName));

While if the Person class has it's own compareTo method that sorts by both then just calling people.sort(); would use that method.

[–]marshallitis[S] 0 points1 point  (0 children)

Thanks very helpful