Java - TreeSet and hashCode()

I have a quick question about [`TreeSet`][1] collections and [`hashCode`][2] methods. I have a `TreeSet` and I'm adding objects to it, before I add an object, I check to see if it exists in the `TreeSet` using the [`contains`][3] method. I have 2 distinct objects, each of which produce a distinct hashCode using my implementation of the 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 for a particular run are: 76126352 and 76126353 (the objects only differ by one digit in one attribute). The contains method is returning true for these objects, even though the hashCodes are different. Any ideas why? This is really confusing and help would really be appreciated. [1]: http://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html [2]: http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode-- [3]: http://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html#contains-java.lang.Object-

以上就是Java - TreeSet and hashCode()的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏