Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to freeze a HashMap to prevent further changes?

The question is pretty much self-explanatory. I have a data structure (I mentioned a HashMap but it could be a Set or a List also) which I initially populate:

Map<String, String> map = new HashMap<String, String>();

for( something ) {
  map.put( something );
}

After the structure has been populated, I never want to add or delete any items:

map.freeze();

How could one achieve this using standard Java libraries?

like image 896
gdiazc Avatar asked Jun 11 '13 19:06

gdiazc


People also ask

What is persistent HashMap?

The Persistent-HashMap is basically a persistent version of the Java HashMap class. Warning: It is not under active development, and has not been used in a production environment. Persistent-HashMap can be found in maven central.

Does HashMap preserve order?

HashMap does not maintains insertion order in java. Hashtable does not maintains insertion order in java. LinkedHashMap maintains insertion order in java. TreeMap is sorted by natural order of keys in java.

How do you nullify a HashMap?

HashMap. clear() method in Java is used to clear and remove all of the elements or mappings from a specified HashMap. Parameters: The method does not accept any parameters. Return Value: The method does not return any value.

Can I use HashMap where multiple threads are accessing updating it explain further?

— Hashmap can solve performance issue by giving parallel access to multiple threads reading hashmap simultaneously. But Hashmap is not thread safe, so what will happen if one thread tries to put data and requires Rehashing and at same time other thread tries to read data from Hashmap, It will go in infinite loop.


1 Answers

The best you can do with standard JDK libraries is Collections.unmodifiableMap().

Note that you must drop the original map reference, because that reference can still be accessed and changed normally. If you passed the old reference to any other objects, they still will be able to change your map.

Best practice:

map = Collections.unmodifiableMap(map);

and make sure you didn't share the original map reference.

like image 57
Petr Janeček Avatar answered Oct 05 '22 23:10

Petr Janeček