The SCJP 6 Study Guide from Bert Bates and Kathy Sierra states on page 554 (among other requirements) that x.hashCode() != y.hashCode() requires that x.equals(y) == false.
But the Javadoc for Object doesn't mention such requirement explicitly. Quote:
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
Should I take what Javadoc says as a material implication, such as eq -> hc? Then there would be no conflict between these two sources.
General contract associated with hashCode() methodIf two objects are equal(according to equals() method) then the hashCode() method should return the same integer value for both the objects.
Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.
Both methods, equals() and hashcode() , are used in Hashtable , for example, to store values as key-value pairs. If we override one and not the other, there is a possibility that the Hashtable may not work as we want, if we use such object as a key.
In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation.
The two statements are equivalent.
Put simply:
As z5h says, the statements are equivalent.
For logical conditions x and y, "x implies y" is the same as "!y implies !x".
"If something is a bus, it's red" is logically equivalent to "if something isn't red, it's not a bus."
This is contraposition.
Should I take what Javadoc says as a material implication, such as eq -> hc.
Yes, that's exactly what it's saying: two objects being equal under equals
implies their hashcodes must be equal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With