简体   繁体   中英

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 convention for them ('gt', 'lt', 'gte', 'lte'). What is it?

查看Comparable接口。

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM