[英]Why not support add/addAll operations for the set returned from entrySet()?
entrySet()
方法在 HashMap/HashTable 中返回Set<Map.Entry<K,V>>
。 为什么 set 不支持 add/addAll 操作,我们知道 key 和 value 条目?
我注意到 jdk1.8 中的java.util.Hashtable.EntrySet.add(Map.Entry<K, V> o)
实现如下:
private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public boolean add(Map.Entry<K,V> o) {
// MyNote: Call AbstractCollection<E>.add(E e) and
// throw UnsupportedOperationException
return super.add(o);
}
}
为什么不实现支持添加操作如下:
private class EntrySet extends AbstractSet<Map.Entry<K,V>> {
/**
* @return <tt>false</tt> if key has exists
*/
public boolean add(Map.Entry<K,V> o) {
V old = Hashtable.this.put(o.getKey(), o.getValue());
return (null == old);
}
}
它是按照 Map.entrySet javadocs:
该集合支持元素移除,通过 Iterator.remove、Set.remove、removeAll、retainAll 和 clear 操作从映射中移除相应的映射。 它不支持 add 或 addAll 操作。
我能看到的一个原因是 EntrySet 不知道它属于哪种集合,因此它不知道允许使用哪种键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.