Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a immutable collection from java HashMap?

I need to get a collection from the java HashMap without the changes in the map reflecting in the collection later . I wanted to use Collection.toArray() to achieve this , but its not working . The resultant Object[] is also changing (javadocs say that The returned array will be "safe" in that no references to it are maintained by this collection ) . Any simple way to achieve this?

like image 500
sanre6 Avatar asked Jan 28 '12 05:01

sanre6


People also ask

Is Java HashMap immutable?

ImmutableMap, as suggested by the name, is a type of Map which is immutable. It means that the content of the map are fixed or constant after declaration, that is, they are read-only. If any attempt made to add, delete and update elements in the Map, UnsupportedOperationException is thrown.

How do you make a hash map immutable?

We used to use the unmodifiableMap() method of Collections class to create unmodifiable(immutable) Map. Map<String,String> map = new HashMap<String, String>(); Map<String,String> immutableMap = Collections. unmodifiableMap(map); Lets test this in JShell.


1 Answers

Its not possible to do this with a single API call, you need to utilize deep cloning. Clones won't be changed when you make changes to the original. This topic has been discussed on SO before, see How to clone ArrayList and also clone its contents? and Deep clone utility recomendation.

like image 137
Bhesh Gurung Avatar answered Oct 27 '22 08:10

Bhesh Gurung