Map.Entry 在 HashMap 实现中是如何使用的?

How is Map.Entry used in HashMap implementation?

我想知道 Map.Entry 是如何像 HashMap 这样在 Map 实现中使用的。下面是 HashMap 如何在 jdk8,

中实现的代码
public interface Map<K, V> {
    interface Entry<K, V> {
        ...
    }
}

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {

    static class Node<K,V> implements Map.Entry<K,V> {
        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
    }

    transient Node<K,V>[] table;

}

我有 2 个问题。

  1. 根据javadocMap.Entrypublic static interface,如public static interface Map.Entry<K,V>。为什么上面的interface Entry<K, V>中少了static? javadoc 是否仅指 Oracle jdk?

  2. 关于static关键字,我的理解是内部Map.Entry对象,table的元素类型,没有引用HashMap 因为 Nodestatic class。 table 变量是 static 吗?如果 tablestatic,那么所有 HashMap class 对象将共享相同的 table;这听起来不对。不是每个 HashMap 对象都有不同的内存存储来托管它们的内容吗?

Why is static missing in above interface Entry<K, V>?

来自JLS:

9.5. Member Type Declarations

A member type declaration in an interface is implicitly public and static. It is permitted to redundantly specify either or both of these modifiers.

About the static keyword, my understanding is that internal Map.Entry object, table's element type, doesn't have a reference to the HashMap because Node is a static class.

它没有参考,因为它不需要参考。您将需要阅读哈希映射数据结构以了解其工作原理。如果您询问 Node 是否可以引用 到地图,那么可以,如果它传递给它(通过构造函数或方法)。如果您询问 Node 是否可以访问 封闭地图,那么不会,因为如您所说,Node 是静态的。如果您尝试执行

之类的操作,您将遇到错误
static class Node<K,V> implements Map.Entry<K,V> {

    HashMap<K,V> map = HashMap.this;
}

No enclosing instance of the type HashMap is accessible in scope。如果 Node 不是 static,则代码将编译。

Is the table variable static?

不是,是transient,也就是说不会通过Serializable接口的协议进行序列化。

Doesn't each HashMap object have distinct memory storage to host their contents?

是的,那是存储 tableentrySetkeySetvalues(后两个在超类中)等内容的地方。