Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections.unmodifiablemap() and collections where reads also modify

This is more a curiosity question than anything. Say I supply a LinkedHashMap with access ordering set to true to Collections.unmodifiableMap(). Since reads are actually modifying the map. Does it mean there are cases where the view returned by unmodifiableMap() is actually modifiable?

public class MyApp {

   /**
   * @param args
   */    
   public static void main(String[] args)    {
     Map<String, String> m = new LinkedHashMap<String,
      String>(16,.75f,true);
      Collections.unmodifiableMap(m);    

    }

}

like image 870
nsfyn55 Avatar asked Feb 23 '23 22:02

nsfyn55


2 Answers

The Map is modifying itself. Collections.unmodifiableMap() only provides a decorator for the Map which disallows modifications, it does not make the Map itself unmodifiable.

like image 186
Christoffer Hammarström Avatar answered Feb 26 '23 12:02

Christoffer Hammarström


Collections.unmodifiableMap returns a new Map that throws exceptions when you try to modify it, using the existing Map that you passed in as a backing collection. It doesn't change the semantics of the existing Map.

like image 43
A Lee Avatar answered Feb 26 '23 12:02

A Lee