public class KeySetImmutable {
public static void main(String[] args) {
Map<String, String> hashMap = new HashMap<>();
hashMap.put("Key1", "String1");
hashMap.put("Key2", "String2");
hashMap.put("Key3", "String3");
hashMap.put("Key4", "String4");
Set<String> keySet = hashMap.keySet();
keySet.add("Key4");
System.out.println(hashMap.keySet());
System.out.println(keySet);
}
}
In the above code keySet.add("Key4") throws java.lang.UnsupportedOperationException. Does it mean this particular instance of Set is a special implementation that prevents addition of keys? How is the underlying implementation achieving this?
Whereas keySet.remove("Key3"); works fine and removes the element from the HashMap as well.
keySet()returns a specificSetimplementation that overridesremove()but inheritsAbstractSet'sadd(), which inheritsAbstractCollection'sadd(), which throwsUnsupportedOperationException.Note that these are just implementation details of a specific JDK version.
The important thing is what the Javadoc of
keySet()states: