gpt4 book ai didi

java - List.retainAll() 内部使用 HashMap 吗?

转载 作者:行者123 更新时间:2023-12-01 16:35:11 30 4
gpt4 key购买 nike

我故意违反了 hashCode 契约,该契约规定,如果我们在类中重写 equals() ,我们也必须重写 hashCode() ,并且我正在做确保没有与哈希相关的数据结构(例如 HashMapHashSet 等)使用它。问题是我担心列表的 removeAll()containsAll() 等方法可能会在内部使用 HashMap,在这种情况下,因为我没有重写 hashCode () 在我的类中,它们的功能可能会中断。

有人可以证实我的怀疑是否有效吗?这些类包含许多用于相等比较的字段,我必须想出一种有效的技术来使用所有这些字段来获取 hashCode。我确实不需要它们在任何与哈希相关的操作中,因此,我试图避免实现 hashCode()

最佳答案

来自 AbstractCollection.retainAll()

 * <p>This implementation iterates over this collection, checking each
* element returned by the iterator in turn to see if it's contained
* in the specified collection. If it's not so contained, it's removed
* from this collection with the iterator's <tt>remove</tt> method.

public boolean retainAll(Collection<?> c) {
boolean modified = false;
Iterator<E> e = iterator();
while (e.hasNext()) {
if (!c.contains(e.next())) {
e.remove();
modified = true;
}
}
return modified;
}

关于java - List.retainAll() 内部使用 HashMap 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9976645/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com