I have seen classes which implement both Comparable and Comparator. What does this mean? Why would I use one over the other?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Comparable lets a class implement its own comparison:
By comparison, Comparator is an external comparison:
In both implementations, you can still choose to what you want to be compared. With generics, you can declare so, and have it checked at compile-time. This improves safety, but it is also a challenge to determine the appropriate value.
As a guideline, I generally use the most general class or interface to which that object could be compared, in all use cases I envision... Not very precise a definition though ! :-(
Comparable<Object>
lets you use it in all codes at compile-time (which is good if needed, or bad if not and you loose the compile-time error) ; your implementation has to cope with objects, and cast as needed but in a robust way.Comparable<Itself>
is very strict on the contrary.My annotation lib for implementing Comparable and Comparator:
Click the link to see more examples. compamatic
Difference between Comparator and Comparable interfaces
Comparable
is used to compare itself by using with another object.Comparator
is used to compare two datatypes are objects.The text below comes from Comparator vs Comparable
Comparable
A comparable object is capable of comparing itself with another object. The class itself must implements the
java.lang.Comparable
interface in order to be able to compare its instances.Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the
java.util.Comparator
interface.Comparable
is usually preferred. But sometimes a class already implementsComparable
, but you want to sort on a different property. Then you're forced to use aComparator
.Some classes actually provide
Comparators
for common cases; for instance,String
s are by default case-sensitive when sorted, but there is also a staticComparator
calledCASE_INSENSITIVE_ORDER
.