Java - TreeSet and hashCode() -
i have quick question treeset
collections , hashcode
methods. have treeset
, i'm adding objects it, before add object, check see if exists in treeset
using contains
method.
i have 2 distinct objects, each of produce distinct hashcode using implementation of hashcode method, example below:
public int hashcode() { int hash = 7; hash = hash * 31 + anattribute.hashcode(); hash = hash * 31 + anotherattribute.hashcode(); hash = hash * 31 + yetanotherattribute.hashcode(); return hash; }
the hashcodes particular run are: 76126352 , 76126353 (the objects differ 1 digit in 1 attribute).
the contains method returning true these objects, though hashcodes different. ideas why? confusing , appreciated.
treeset not use hashcode
@ all. uses either compareto
or comparator passed constructor. used methods contains find objects in set.
so answer question compareto method or comparator defined 2 objects in question considered equal.
from javadocs:
a treeset instance performs element comparisons using compareto (or compare) method, 2 elements deemed equal method are, standpoint of set, equal.
Comments
Post a Comment