Should the 'equals' (Object) method be overridden when overriding hashCode() in Java? -
this question has answer here:
should equals
(object) method overridden when overriding hashcode() in java?
i have read contract overriding equals
, should override hashcode
. vice versa true?
i thinking of scenario don't compare objects, no equals method.
yes, should overridden. if think need override hashcode()
, need override equals()
, vice versa. general contract of hashcode() is:
whenever invoked on same object more once during execution of java application, hashcode method must consistently return same integer, provided no information used in equals comparisons on object modified. integer need not remain consistent 1 execution of application execution of same application.
if 2 objects equal according equals(object) method, calling hashcode method on each of 2 objects must produce same integer result.
it not required if 2 objects unequal according equals(java.lang.object) method, calling hashcode method on each of 2 objects must produce distinct integer results. however, programmer should aware producing distinct integer results unequal objects may improve performance of hashtables.
Comments
Post a Comment