Possible Duplicate:
In Java, why must equals() and hashCode() be consistent?
I read that one should always hascode() when overriding equals().
Can anyone give a practical example of why it might be wrong otherwise?
i.e. Problems that might arise when overriding equals() but not hashCode().
Is it necessary to write a robust hasCode() function whenever we override equals()? Or a trivial implementation is enough?
For example,
A poor implementation such as the below is good enough to satisfy the contract between equals() & hashCode()?
public int hashCode() {
return 91;
}
equals()andhashCode()are used conjunctively in certain collections, such asHashSetandHashMap, so you have to make sure that if you use these collections, you overridehashCodeaccording to the contract.If you don’t override
hashCodeat all, then you’ll have problems withHashSetandHashMap. In particular, two objects that are “equal” may be put in different hash buckets even though they should be equal.If you do override
hashCode, but do so poorly, then you’ll have performance issues. All your entries forHashSetandHashMapwill be put into the same bucket, and you’ll lose the O(1) performance and have O(n) instead. This is because the data structure essentially becomes a linearly-checked linked list.As for breaking programs outside of these conditions, it’s not likely, but you never know when an API (especially in 3rd-party libraries) is going to depend on this contract. The contract is upheld for objects that don’t implement either of them, so it’s conceivable that a library may depend on this somewhere without using hash buckets.
In any case, implementing a good
hashCodeis easy, especially if you’re using an IDE. Eclipse and Netbeans both have the ability to generateequalsandhashCodefor you in a way that all contracts are followed, including the inverse rules ofequals(the assertion thata.equals(b) == b.equals(a)). All you need to do is select the fields you want to be included and go.