Java value object comparison methods
I'm new to Java and trying to learn.
Java doesn't have operator overloading, so when coding a value object I understand that you need to compare objects with an overridden 'equals' method instead of the == operator, but I have yet to read about the other methods you need to override. What about the equivalent methods for the other common operators: >, <, >=, and <=. Do these methods need to be overridden, or do I have to create them if I need them. If I have to create these methods, there must be some standard naming conve开发者_运维技巧ntion for them ('gt', 'lt', 'gte', 'lte'). What is it?
Look into the Comparable
interface.
You need to override hashCode()
(used by all hash collections) and equals()
. It's a rule that if a.equals(b)
, a.hashCode()
should equal b.hashCode()
.
For comparisons you may implement the interface Comparable
. For this interface you'll need to implement a compareTo
method which is an equivalent of <, =, > (note that a.compareTo(b) == 0
does NOT imply or require that a.equals(b)
!). Implementing Comparable
is optional and only useful if you're interested in sorting or certain order-based collections such as TreeSet
.
In java, the Comparable interface is meant exactly for that. For a "canonical example", have a look into the the java.lang.Integer
class and see the implementation of equals()
, hashCode()
and compareTo()
. Also, have a look at the JavaDoc info available for these methods in java.lang.Object
and java.lang.Comparable
.
精彩评论