gpt4 book ai didi

Java HashMap、HashSet、EntrySet 实现中的关系

转载 作者:行者123 更新时间:2023-11-30 06:30:28 29 4
gpt4 key购买 nike

HashMap在java中有一个函数entrySet()返回 Set<Map.Entry<K,V>>

The set is backed by the map, so changes to the map are reflected in the set, and vice-versa

根据文档,我认为在 HashMap 创建时,一个HashSet正在创建,并且当对 HashMap 执行任何操作时都会更新它.

但是,我也知道 implementationHashSetHashMap 支持其中键是唯一的,值是相同的单例。

  1. 所以EntrySet不得在 HashMap 的构造函数中创建,需要偷懒吗?如果没有,new HashMap()调用new HashSet()这再次调用 new HashMap()直到堆爆炸。

  2. 感觉就像EntrySet可以使用EntrySet.Key.hashCode()EntrySet.Key.equals()对于哈希运算,这意味着 HashMapEntrySet的实现看起来与实际的 HashMap 非常相似,只不过 key 的类型不同 KMap.Entry<K,V> 。那我们为什么要保留两份相似的副本呢?我们可以只使用 EntrySet (一个HashMap)?

最佳答案

Based on the doc, I would think that at creation time of HashMap, a HashSet is being created, and it is updated when any operation is performed on HashMap.

该文档并没有暗示任何类似的内容。它只是指定集合的​​行为。

EntrySet

  • 缓存: map 将其实例保存在内存中,当第一次请求时,它会被创建(并返回)。从那里开始,任何对它的请求都会返回它。
  • 代理(或委托(delegate)人):EntrySet是一个内部类(非静态),因此它与其包含类相关联 - HashMap 。当它返回时,对其的任何操作都会委托(delegate)给映射,就像 entrySet.remove(o) { HashMap.this.remove(o); } 一样。 .
  • map 的表示(或 View )。 map 可以用多种方式表示。例如,您可以将映射表示为 2 个键和值列表(长度相同)。 EntrySet将其表示为单个对列表。由于 map 类似于矩阵结构,因此您可以考虑将其视为行列表或列列表。

So EntrySet must not be created in the constructor of HashMap, it needs to be lazy?

它可以在构建 HashMap 时创建但那时它是空的,所以没有太多意义。也不能保证它会被需要,所以没有理由创建它。

If not, new HashMap() invokes new HashSet() which again invokes new HashMap() until the heap explodes.

HashSet不参与。两者EntrySetHashSetAbstractSet 的直接子类。无论如何,为什么集合构造函数会调用映射构造函数?

It feels like the EntrySet can use EntrySet.Key.hashCode() and EntrySet.Key.equals() for hash operations...

EntrySet本身不需要散列任何内容,它使用 HashMaphash()方法。

... which implies that the HashMap in EntrySet's implementation looks very similar to the actual HashMap...

EntrySet的实现不保留 HashMap 的副本,它由于是它的内部类而与其关联。

... except that the key is of different type K vs Map.Entry<K,V>.

EntrySet<K, V> 中 key 的类型与 HashMap<K, V> 中的相同.

Then why are we keeping two similar copies? can we just use the EntrySet (one HashMap)?

参见上文,没有副本。

我建议您引用source codeEntrySet ,但您在 IDE 中检查它会更容易。

关于Java HashMap、HashSet、EntrySet 实现中的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46261339/

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