Java : Comparable vs Comparator

JavaComparatorComparable

Java Problem Overview


> Possible Duplicates:
> difference between compare() and compareTo()
> Java: What is the difference between implementing Comparable and Comparator?

What are the keys differences between Comparable and Comparator.

and which is preferred over the other in what scenarios?

Thanks

Updated - GOOD LINK WITH EXAMPLE!!

http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html

Java Solutions


Solution 1 - Java

When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.

A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.

For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.

In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

Solution 2 - Java

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondaydreamerView Question on Stackoverflow
Solution 1 - JavaAndyView Answer on Stackoverflow
Solution 2 - JavaJustin NiessnerView Answer on Stackoverflow