Why not support add/addAll operations for the set returned from entrySet()?

Viewed 353

The entrySet() method returns Set<Map.Entry<K,V>> in HashMap/HashTable. Why the set does not support add/addAll operations, we know key and value entry?

I noticed the java.util.Hashtable.EntrySet.add(Map.Entry<K, V> o) implementation as follow in Jdk1.8:

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);
    }
}

Why does not implement to support add operation like follow:

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);
    }
}
2 Answers

It is in accordance with Map.entrySet javadocs:

The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

One reason I can see is that EntrySet is not aware of what kind of collection it belongs to, therefor it does not know what kind of keys are allowed.

Related