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

Map<>使用 for 循环进行迭代时


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)


沧海一幻觉
浏览 331回答 3
3回答

HUH函数

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

FFIVE

方法 java.util.HashMap.entrySet() 返回一个类 java.util.HashMap.EntrySet,它本身不实现方法 Set.add()。要将对象添加到集合中,您必须使用方法 myMap.put(entry.getKey(), entry.getValue())。方法 entrySet() 仅用于读取数据,不用于修改。

精慕HU

问题是你add()在entrySet()of上调用方法,HashMap并且在那个类中没有这样的实现,只有在它的超类中。从HashMap源代码:public Set<Map.Entry<K,V>> entrySet() {&nbsp; &nbsp; Set<Map.Entry<K,V>> es;&nbsp; &nbsp; return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;}final class EntrySet extends AbstractSet<Map.Entry<K,V>> {// there is no add() override}因为add()方法没有被覆盖(既不是 inHashMap.EntrySet也不是 in AbstractSet),所以AbstractCollection将使用from 方法,它具有以下定义:public boolean add(E e) {&nbsp; &nbsp; throw new UnsupportedOperationException();}另外,查看entrySet()Javadoc:(...) set 支持元素移除,通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear 操作从映射中移除对应的映射。它不支持 add 或 addAll 操作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java