【发布时间】:2021-05-19 05:44:11
【问题描述】:
我有一个类有自己的 hashCode() 方法。我正在将此类添加到 HashSet。如何在不知道对象本身的情况下通过其 hashCode 删除项目?
例如,如果我有以下代码
HashSet<Data> set = new HashSet<>();
set.add(new Data(10, 5));
...
class Data {
public int importantVal;
public int notImportantVal;
//... constructor ...
@Override
public int hashCode() {
return importantVal;
}
}
我知道 Data 对象的importantVal,但不知道对象本身。我将如何删除它? set.remove(10) 不起作用。
我能想到的最佳解决方案是如果importantVal 相同,也覆盖equals() 以返回,然后执行set.remove(new Data(10, anyPlaceholderValue))
我正在寻找 O(1) 的解决方案。我显然知道如何遍历 HashSet 并检查每个元素,但这太慢了。
【问题讨论】:
-
您确实意识到哈希码可能不是唯一的,对吧?一个集合中可能有多个不相等的对象,它们都具有相同的哈希码。在这种情况下,您要删除所有这些吗?
-
“我能想到的最佳解决方案是,如果
importantVal相同,则也覆盖equals()以返回”。那么equals不是现在就这样实现了吗?那么equals是如何实现的呢? -
我认为如果 importantVal 对所有对象都是唯一的,那么 set.remove(new Data(10, anyPlaceholderValue)) 将给出 O(1) 复杂性。但前提是equals方法定义正确。
-
听起来你应该使用
Map<Integer, Data>而不是 set。 -
你的 hashCode 和 equals 方法应该绝对遵循相同的逻辑?!
标签: java hash set hashset hashcode