Santoshkumar Kalasa Santoshkumar Kalasa - 1 year ago 85
Java Question

Which implementation of set does map.keyset() returns, and why it does not support add operaton on it?

Why this is throwing


public static void main(String[] args) {
Map<String,String> map=new HashMap<String,String>();
map.put("a", "a value");
Set<String> set=map.keySet();

Answer Source

The Map interface does not define which implementation of Set the keySet() should return. Specifically, HashMap#keySet() returns an instance of the inner class java.util.Map$KeySet. The returned Set represents the keys of the Map, so adding to it would, in essence, mean adding a key to the map. Ultimately, this is a design decision the JDK developers took, but IMHO, it's the right one. Assume this operation was allowed - What would this operation do? Add a key to the map pointing to a null value? What if you extend Map to perform some operation on the value when it's added? How would such a scenario be treated?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download