Wednesday, December 28, 2011

Comparable vs. Comparator

http://grdurand.com/static/presentation_four/comparable.html

Classes should implement the Comparable interface to control their natural ordering.

Objects that implement Comparable can be sorted by Collections.sort() and Arrays.sort() and can be used as keys in a sorted map or elements in a sorted set without the need to specify aComparator.

« Interface »
Comparable
+ compareTo(Object) : int
compareTo() compares this object with another object and returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the other object.

Use Comparator to sort objects in an order other than their natural ordering.

« Interface »
Comparator
+ compare(Object, Object) : int
+ equals(Object) : boolean
compare() compares its two arguments for order, and returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

No comments: