java - For adding an object in set, is it necessary to override equals and hashcode both.? -


this question has answer here:

recently interviewer asked me have class have overriden equals() method have not overridden hashcode() method.

now necessary override hashcode() method too.?

what happen if don't override hashcode method, set maintain unique property of not allowing duplicates.?

the question internal implementation of set , here confusion if 2 objects return different hashcode(), according me equals() won't checked , unique property of set violated if 2 objects came out equal.

is true.?

the easiest way understand see hashcodes buckets.when store objects in sets go these buckets according calculated hashcode.

when override equals , 1 object equal another, should land in same bucket.

however won't case since haven't overriden hashcode method ensure this.

so jvm try search object in wrong bucket. won't find , result you'll have duplicates. (btw interviews starting , scared!)


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -