Why is Java Comparable
used? Why would someone implement Comparable
in a class? What is a real life example where you need to implement comparable?
相关问题
- 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 defines a natural ordering. What this means is that you're defining it when one object should be considered "less than" or "greater than".
Suppose you have a bunch of integers and you want to sort them. That's pretty easy, just put them in a sorted collection, right?
But now suppose I have some custom object, where sorting makes sense to me, but is undefined. Let's say, I have data representing districts by zipcode with population density, and I want to sort them by density:
Now the easiest way to sort them is to define them with a natural ordering by implementing Comparable, which means there's a standard way these objects are defined to be ordered.:
Note that you can do the equivalent thing by defining a comparator. The difference is that the comparator defines the ordering logic outside the object. Maybe in a separate process I need to order the same objects by zipcode - in that case the ordering isn't necessarily a property of the object, or differs from the objects natural ordering. You could use an external comparator to define a custom ordering on integers, for example by sorting them by their alphabetical value.
Basically the ordering logic has to exist somewhere. That can be -
in the object itself, if it's naturally comparable (extends Comparable -e.g. integers)
supplied in an external comparator, as in the example above.
Most of the examples above show how to reuse an existing comparable object in the compareTo function. If you would like to implement your own compareTo when you want to compare two objects of the same class, say an AirlineTicket object that you would like to sort by price(less is ranked first), followed by number of stopover (again, less is ranked first), you would do the following:
Here is a real life sample. Note that
String
also implementsComparable
.later..
For example when you want to have a sorted collection or map
An easy way to implement multiple field comparisons is with Guava's ComparisonChain - then you can say
instead of
Comparable is used to compare instances of your class. We can compare instances from many ways that is why we need to implement a method
compareTo
in order to know how (attributes) we want to compare instances.Dog
class:Main
class:Here is a good example how to use comparable in Java:
http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html?page=2