From charlesreid1

No edit summary
No edit summary
 
Line 15: Line 15:
(Another interesting use case is comparing objects of different types.)
(Another interesting use case is comparing objects of different types.)


==comparators over comparable==
Use comparators - they are much more flexible. The comparator itself is easy to define. Providing a default comparator is also a good move.





Latest revision as of 23:08, 22 June 2017

What are they?

Comparable - an object is comparable if it can be compared with other objects of a given type, done by extending Comparable and implementing compareTo method

Comparator - a comparator is a standalone object whose sole purpose is to compare two objects.

why comparable

The advantage of using a comparable is that you can compare objects directly, and define the comparison behavior as being inherent to the object itself. This is obviously the "normal" model.

why comparator

Comparators offer some interesting advantages. First, by using an object to perform comparisons, you abstract yourself from the implementation details of how the comparison is performed. You define a comparator object that defines how the comparison works, somewhere in your own code. You can then pass that comparator into another class and allow it to use your own, custom criteria for performing comparisons.

(Another interesting use case is comparing objects of different types.)

comparators over comparable

Use comparators - they are much more flexible. The comparator itself is easy to define. Providing a default comparator is also a good move.