Suppose SortOf A
has code = "AA"; bal=2; rate=2
and SortOf B
has code = "A"; bal=4; rate=2;
Then for A
, code.length = 2
, bal = 2
, rate = 2
and B
has code.length = 1
, bal = 4
, rate=2
. Then A.equals(B)
but A.hashCode() != B.hashCode()
Apart from your other issues with the code, I believe this violates the contract.
Edited to add: Actually, it may be that this definition of equals()
technically satisfies the contract for Object.equals()
, which makes no demand on consistency with hashCode()
. It's the contract for Object.hashCode()
whose contract demands consistency with equals()
. What's that about small minds and foolish consistency...? <andersoj leaves to apply to law school>
This equals()
is reflexive, symmetric, transitive, consistent. I guess it violates the contract because .equals(null)
throws an exception rather than returning false
as required. All the equals()
spec says about hashCode()
is:
Note that it is generally necessary to
override the hashCode
method whenever
this method is overridden, so as to
maintain the general contract for the
hashCode
method, which states that
equal objects must have equal hash
codes.