【发布时间】:2018-11-01 11:21:49
【问题描述】:
在使用 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)
【问题讨论】:
-
myMap 是什么类型的?
-
@OHGODSPIDERS 我在这里使用了 HashMap
标签: java dictionary entryset