Map<> 中 entrySet() 的 add() 方法

add() method on entrySet() in Map<>

在使用 for 循环

迭代 Map<>
for(Map.Entry<K,V> mapEntry : myMap.entrySet()){
    // something
}

我找到了entrySet()方法returns一套Entry<K,V>

所以它有add(Entry<K,V> e)方法

然后我创建了一个实现 Map.Entry<K,V> 的 class 并尝试插入如下对象

    public final class MyEntry<K, V> implements Map.Entry<K, V> {

    private final K key;
    private V value;

    public MyEntry(K key, V value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public K getKey() {
        return key;
    }

    @Override
    public V getValue() {
        return value;
    }

    @Override
    public V setValue(V value) {
        V old = this.value;
        this.value = value;
        return old;
    }

}


Entry<String, String> entry = new MyEntry<String, String>("Hello", "hello");
myMap.entrySet().add(entry); //line 32

没有编译错误, 但它会引发运行时错误

    Exception in thread "main"
java.lang.UnsupportedOperationException
    at java.util.AbstractCollection.add(AbstractCollection.java:262)
    at com.seeth.AboutEntrySetThings.main(AboutEntrySetThings.java:32)

来自 entrySet() 方法上的 JavaDoc:

The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

该方法的 javadoc https://docs.oracle.com/javase/10/docs/api/java/util/AbstractCollection.html#add(E)

This implementation always throws an UnsupportedOperationException.

然后子类覆盖它并且public void add(int size, E element); HashMap 中的子类 EntrySet 没有覆盖它。

问题是您在 HashMapentrySet() 上调用 add() 方法,class 中没有这样的实现,仅在其超级classes.

来自HashMap源代码:

public Set<Map.Entry<K,V>> entrySet() {
    Set<Map.Entry<K,V>> es;
    return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
}

final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
// there is no add() override
}

因为add()方法没有被覆盖(在HashMap.EntrySetAbstractSet中都没有),将使用AbstractCollection中的方法,其定义如下:

public boolean add(E e) {
    throw new UnsupportedOperationException();
}

此外,查看 entrySet() Javadoc:

(...) The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

方法java.util.HashMap.entrySet()returns一个classjava.util.HashMap.EntrySet,它本身没有实现方法Set.add().
要将对象添加到集合中,必须使用方法 myMap.put(entry.getKey(), entry.getValue()).

方法entrySet()只用于读取数据,不用于修改。