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
user166390
source share