The modifiable map may still change. This is just a look at the map being modified, and changes in the support map will be visible through the unmodified map. An unmodifiable map only prevents modifications for those who have only a link to an unmodifiable representation:
Map<String, String> realMap = new HashMap<String, String>(); realMap.put("A", "B"); Map<String, String> unmodifiableMap = Collections.unmodifiableMap(realMap); // This is not possible: It would throw an // UnsupportedOperationException //unmodifiableMap.put("C", "D"); // This is still possible: realMap.put("E", "F"); // The change in the "realMap" is now also visible // in the "unmodifiableMap". So the unmodifiableMap // has changed after it has been created. unmodifiableMap.get("E"); // Will return "F".
In contrast, the ImmutableMap from Guava is really unchanged: it is a real copy of this map, and no one can modify this ImmutableMap in any way.
Update :
As pointed out in comment , an immutable map can also be created with a standard API using
Map<String, String> immutableMap = Collections.unmodifiableMap(new LinkedHashMap<String, String>(realMap));
This will create an unmodifiable view of the true copy of this map and, thus, beautifully emulates the characteristics of ImmutableMap , without adding dependencies to Guava.
Marco13 Mar 25 '14 at 13:55 2014-03-25 13:55
source share