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

时间:2018-11-01 11:21:50

标签: java dictionary entryset

使用for循环迭代Map<>

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

我发现entrySet()方法返回了一组Entry<K,V>

因此它具有add(Entry<K,V> e)方法

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

    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)

4 个答案:

答案 0 :(得分:2)

使用entrySet()方法的JavaDoc:

  

该集合支持元素删除,该元素通过Iterator.remove,Set.remove,removeAll,retainAll和clear操作从映射中删除相应的映射。它不支持add或addAll操作。

答案 1 :(得分:0)

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

  

此实现始终抛出UnsupportedOperationException。

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

答案 2 :(得分:0)

问题是您正在add()的{​​{1}}上调用entrySet()方法,并且该类中没有这样的实现,只有在其超类中

来自HashMap源代码:

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.EntrySet中均未被覆盖),将使用AbstractSet中的方法,其定义如下:< / p>

AbstractCollection

还要查看entrySet() Javadoc

  

(...)集合支持元素删除,该元素通过Iterator.remove,Set.remove,removeAll,retainAll和clear操作从映射中删除相应的映射。 它不支持add或addAll操作。

答案 3 :(得分:0)

方法java.util.HashMap.entrySet()返回一个类java.util.HashMap.EntrySet,该类本身未实现方法Set.add()。
要将对象添加到集合中,必须使用方法myMap.put(entry.getKey(),entry.getValue())。

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