繁体   English   中英

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

[英]How is Map.Entry used in HashMap implementation?

我有一个关于Map.Entry如何在 Map 实现中使用的问题,例如HashMap 这是在HashMap中如何实现HashMap的代码,

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. According to javadoc , Map.Entry is a public static interface , as public static interface Map.Entry<K,V> . 为什么上面的interface Entry<K, V>中缺少static javadoc 是否仅引用 Oracle jdk?

  2. About the static keyword, my understanding is that internal Map.Entry object, table 's element type, doesn't have reference to the HashMap because Node is a static class. table变量是static吗? 如果tablestatic ,那么所有HashMap class 对象将共享同一个table 这听起来不对。 不是每个HashMap object 都有不同的 memory 存储来托管它们的内容吗?

为什么上面的interface Entry<K, V>中缺少static

JLS

9.5。 成员类型声明

接口中的成员类型声明是隐式public的和static 允许冗余指定这些修饰符中的一个或两个。

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.

它没有参考,因为它不需要参考。 您需要阅读 hash map 数据结构以了解其工作原理。 如果您询问Node是否可以引用map,那么是的,如果它传递给它(通过构造函数或方法)。 如果您询问Node是否可以访问封闭的 map,那么不,因为正如您所说, Node是 static。 如果您尝试执行类似的操作,您将得到的错误

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 ,则代码将编译。

表变量是static吗?

不,它是transient的,这意味着它不会通过Serializable接口的协议进行序列化。

不是每个HashMap object 都有不同的 memory 存储来托管它们的内容吗?

是的,这就是tableentrySetkeySetvalues (后两个在超类中)等内容的存储位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM