在迭代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)发布于 2018-11-01 11:30:54
来自JavaDoc on entrySet()方法:
集合支持元素删除,它通过Iterator.remove、Set.remove、removeAll、retainAll和clear操作从映射中删除对应的映射。它不支持add或addAll操作。
发布于 2018-11-01 11:34:12
问题是,您在entrySet() of HashMap和上调用了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中),所以将使用来自AbstractCollection的方法,该方法具有以下定义:
public boolean add(E e) {
throw new UnsupportedOperationException();
}同时,看看 Javadoc
(...)集合支持元素删除,它通过Iterator.remove、Set.remove、removeAll、retainAll和clear操作从映射中删除对应的映射。它不支持添加或addAll操作.
发布于 2018-11-01 12:02:30
方法java.util.HashMap.entrySet()返回类java.util.HashMap.EntrySet,该类本身不实现方法Set.add()。
要向集合添加对象,必须使用方法myMap.put(entry.getKey()、entry.getValue())。
方法entrySet()仅用于读取数据,而不是用于修改。
https://stackoverflow.com/questions/53100262
复制相似问题