在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)