Question

Am trying out adding entry to unmodifiable Map, JVM catch UnsupportedOperationException when adding entry to a subview of original Map, but JVM does not care about direct adding to the original view, code speaks :

ConcurrentMap<String, Integer> origView= new ConcurrentHashMap<String, Integer>();
                Map<String,Integer> subView = Collections.unmodifiableMap(origView);
                origView.put("s", 44); // ok
                subView.put("p", 77); // java.lang.UnsupportedOperationException

However Documentation of Collections.unmodifiableSortedMap() says :

Attempts to modify the returned sorted map, whether direct, via its collection views, or via its subMap, headMap, or tailMap views, result in an UnsupportedOperationException.

please lend hand, thanks .

Was it helpful?

Solution

"Attempts to modify the returned sorted map. ..."

It will only throw an UnsupportedOperationException on the Map returned from the unmodifiableMap(...) call, which does not include the original Map.

The Map that gets returned from unmodifiableMap(...) is not the same as the original Map.

OTHER TIPS

Collections.unmodifiableMap() returns an unmodifiable view of the original map; it does not change the original map in any way. That means that the original map is still modifiable. You will only get an exception if you try to modify the unmodifiable view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top