How to freeze a HashMap to avoid other changes?
source link: https://www.codesd.com/item/how-to-freeze-a-hashmap-to-avoid-other-changes.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How to freeze a HashMap to avoid other 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?
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.
Related Articles
How to browse a HashMap while avoiding ConcurrentModificationException
How to freeze the repainted web browser while changing the visibility of items?
How to sort a Hashmap by Key String?
How to freeze the screen?
How to freeze the rotation of a Rigidbody programmatically?
How to freeze numbers when you have reached a number in a matrix
How to freeze the header and footer in ListView
How to convert a HashMap of objects into an ArrayList of Strings
How can I store HashMaps in mongodb using morphine?
How do I call this function in other parts of my code?
How to freeze the GridView header?
Java - How much does a HashMap.get () call cost?
How to make a SWF file, including other resources to a set of applications in osx?
In GIT, how do you delete a delete file from a commit with other changes?
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK