了解界面Map <K,V>

Yev*_*ago 2 java map

我正在学习地图数据结构知道,我无法理解entrySet() Set<Map.Entry<K,V>>地图界面内部.这应该是嵌套的自引用吗?作为参考,这是java.util.Map<K,V>界面定义的摘录:

public interface Map<K,V> {
    Set<Map.Entry<K,V>> entrySet();
    ...
}
Run Code Online (Sandbox Code Playgroud)

fge*_*fge 5

这应该是嵌套的自引用吗?

不.它只表示无论Map返回什么,因为此方法的结果必须是服从Set接口的对象实例,它反映了这些Map条目的内容.它是一样的.keySet().

两者都是Sets 是有意义的,因为a Map中的条目是唯一的(由于定义的Map.Entry's .equals()/的合同.hashCode()),键也是如此(但对于键,你有责任确保.equals()/ .hashCode()被尊重).

但是,你必须要小心.对于这两种方法,javadoc说:

该集由地图支持,因此对地图的更改将反映在集中,反之亦然.

如果你不小心,这可能会带来麻烦.

看看这个例子:

public static void main(final String... args)
{
    final Map<String, String> map = new HashMap<>();
    map.put("hello", "world");
    map.put("foo", "bar");

    // Create a map entry
    final Map.Entry<String, String> entry
        = new AbstractMap.SimpleEntry<>("foo", "bar");

    // Remove it from the set
    map.entrySet().remove(entry);
    System.out.println("after removing entry: " + map);

    // Remove a key
    map.keySet().remove("hello");
    System.out.println("after removing key: " + map);
}
Run Code Online (Sandbox Code Playgroud)

结果:

after removing entry: {hello=world}
after removing key: {}
Run Code Online (Sandbox Code Playgroud)