How to get immutable collection from java HashMap?

I need to get a collection from java HashMap without changes to the map reflected in the collection later. I wanted to use Collection.toArray () to achieve this, but didn't work. The resulting object [] also changes (javadocs say that the returned array will be "safe" because references to it are not supported by this collection). Any easy way to achieve this?

+8
java collections hashmap
source share
5 answers

It is not possible to do this with a single API call, you need to use deep cloning. Clones will not be changed if you make changes to the original. This topic has been discussed on SO before, see How to clone an ArrayList and also clone its contents? and Deep clone utility recommendation .

+9
source share
+8
source share

You can create unmodifiable map

+2
source share

It is still valid and describes the observed problem (see the bit about which copy is running). However, I am not providing any answer on how to perform a deep copy.

Instead, my suggestion is to design immutable objects, which completely eliminates this problem. In my experience, this works very well for most trivial objects (that is, Objects that are not “containers”), and can simplify the code and reason about it.


From Javadoc for HashMap.values :

Gets a view of the collection of values ​​contained in this map. The collection is supported by the map , so changes to the map are reflected in the collection and vice versa ...

Perhaps it would be useful to create a copy of it?

 HashMap<K,V> map = ....; List<V> values = new ArrayList<V>(map.values()); 

This essentially makes a shallow copy , which is now "separate." However, it is a shallow copy; cloning / copying of contained objects is not performed . (See Answer by βɛƨ Ǥʋʋɢ, if a deep copy is desired: the question itself seems a little vague on this question.)

Happy coding

+2
source share

Create a shallow copy of the source map with HashMap.clone() , and then extract the values ​​from it. This will create new references to the source map objects during the call to clone() ; obviously, changes within the contained objects themselves will still be reflected in the copied collection. If you want this behavior, the only way is to copy the map objects to the collection you need.

0
source share

All Articles