Search code examples
javadictionaryentryset

add() method on entrySet() in Map<>


While iterating Map<> using for loop

for(Map.Entry<K,V> mapEntry : myMap.entrySet()){
    // something
}

I found entrySet() method returns a set of Entry<K,V>

so it has add(Entry<K,V> e) method

then I created a class which implements Map.Entry<K,V> and tried inserting the object like below

    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

there is no compilation error, but it throws a runtime error

    Exception in thread "main"
java.lang.UnsupportedOperationException
    at java.util.AbstractCollection.add(AbstractCollection.java:262)
    at com.seeth.AboutEntrySetThings.main(AboutEntrySetThings.java:32)

Solution

  • From the JavaDoc on entrySet() method:

    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.