Reputation: 807
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?
Upvotes: 9
Views: 18529
Reputation:
The following is still valid and describes the issue observed (see the bit on what sort of copy is performed). I do not, however, provide any answer on how to perform a deep-copy.
Instead, my suggestion, is to design the objects to be immutable, which avoids this issue entirely. In my experience this works really well for most trivial objects (that is, objects which are not "containers") and can simplify code and reasoning about it.
From the Javadoc for HashMap.values
:
Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa...
Perhaps it would be beneficial to create a copy of it?
HashMap<K,V> map = ....;
List<V> values = new ArrayList<V>(map.values());
That, in essence, performs a shallow-copy that is "now separate". However, being a shallow copy, no clone/copy of the contained objects is performed. (See βнɛƨн Ǥʋяʋиɢ's answer if deep-copy semantics are desired: the question itself seems a little vague on the matter.)
Happy coding
Upvotes: 2
Reputation: 8530
Google collections Immutable Map may help you.
see Collections.unmodifiableMap also
Upvotes: 8
Reputation: 19194
Create a shallow copy of the original map whith HashMap.clone()
, then retrieve the values colleation from that. This will create new references to the objects in the original map at the time of the clone()
call; obviously changes inside the contained objects themselves will still be reflected in the copied collection. If you want this behaviour, your only way is to hard copy the map objects in your desired collection.
Upvotes: 0
Reputation: 51030
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.
Upvotes: 10