Java HashSet允许欺骗;问题可比吗? [英] Java HashSet is allowing dupes; problem with comparable?

查看:154
本文介绍了Java HashSet允许欺骗;问题可比吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类Accumulator,它实现了Comparable compareTo方法,我正在尝试将这些对象放入HashSet。

I've got a class, "Accumulator", that implements the Comparable compareTo method, and I'm trying to put these objects into a HashSet.

我将()添加到HashSet,我在调试器中的compareTo方法中看不到任何活动,无论我在哪里设置断点。另外,当我完成add()时,我在Set中看到了几个重复项。

When I add() to the HashSet, I don't see any activity in my compareTo method in the debugger, regardless of where I set my breakpoints. Additionally, when I'm done with the add()s, I see several duplicates within the Set.

我搞砸了什么,这里;为什么不比较,因此允许欺骗?

What am I screwing up, here; why is it not Comparing, and therefore, allowing the dupes?

谢谢,

IVR Avenger

Thanks,
IVR Avenger

推荐答案


我搞砸了什么,这里?

What am I screwing up, here?

HashSet基于 hashCode(),而不是 compareTo()。您可能会将其与 TreeSet 混淆。在这两种情况下,请务必以与其他方法一致的方式实现 equals()

HashSet is based on hashCode(), not on compareTo(). You may be confusing it with TreeSet. In both cases, be sure to also implement equals() in a manner that is consistent with the other method.

这篇关于Java HashSet允许欺骗;问题可比吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆