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?
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.
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.
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.
— 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With