Equals () and hashCode () in Java

The SCJP 6 study guide from Bert Bates and Kathy Sierra states on page 554 (among other requirements) that x.hashCode ()! = Y.hashCode () requires x.equals (y) == false .

But the Javadoc for Object does not mention such a requirement explicitly. Quote:
If two objects are equal in accordance with the equals (Object) method, then calling the hashCode method for each of the two objects should produce the same integer result.

Should I take what Javadoc says as material meaning, for example eq → hc ? Then there will be no conflict between the two sources.

+5
source share
5 answers

As z5h says, the statements are equivalent.

For the logical conditions x and y, x means that y "matches"! y implies x ".

"If something is a bus, it is red" logically equivalent "if something is not red, it is not a bus."

This is a contraposition .

Should I take what Javadok says as a material meaning, such as eq → hc.

Yes, that’s what he says: two objects equal to at equalsimply that their hash codes must be equal.

+13
source

Two statements are equivalent.

Simply put:

  • If two hash codes are different from each other, objects will certainly be different from each other.
  • - , . ( ).
+12

, .

p: x.equals(y)
q: x.hashCode() == y.hashCode()
p implies q
not q implies not p
+5

HashMap.
 1. HashMap - .
 2. - hashcode (.. )

: (, SPObject) - -; SPObject (). . http://www.programcreek.com/2011/07/java-equals-and-hashcode-contract/

hashCode() equals() SPObject, .
2 - SPObject ( "SP" ) SPObject ( "SP" ). .

map.get( SPObject ( "SP" )) null.
map.contains( SPObject ( "SP" )) false.

, hashCode/equals .

hashCode()     |    equals()    | Treated as | Description
No             |      No        | Duplicate  | Stored in different buckets.
                                             | Treated as different object.

Yes            |      No        | Duplicate  | Stored in same bucket.
                                             | Treated as different object. 
                                             | Because, the default(Object) equals method will check only the reference of objects.     

No             |      Yes       | Duplicate  | Stored in different buckets.Treated as different object

Yes(hashlogic) |      Yes       | Unique     | Stored in same bucket.Treated as same object.Efficient.

Yes(constant)  |      Yes       | Unique     | Stored in same bucket.Treated as same object.
                                             | Inefficient, because it will iterate bucket elements for equality check.

+2

hashCode , , , hashCode, , - , , . , , , - , . , , , - , , , . , , , , , .

"" hashCode equals : , X.equals(Y) true, , , . , , , , , , . , -, ; , , . JavaDoc , , , , , , , hashCodereturned by one will also be returned by the other.

0
source

All Articles