I obtain a HashSet from a HashMap and I don’t want that my modifications on the HashSet reflect on the HashMap values.
What’s the best way of doing something like this :
HashSet<Object> hashset = new HashSet((Collection<Object>) hashmap.values());
//Something like ...
hashset.detach();
//Then i can modify the HashSet without modifying the HashMap values
Edit :
I have to modify an element in the HashSet but I don’t want to modify this same element in the HashMap.
Thanks!!!
When you create the
HashSetfromhashMap.values()like this, then it’s already “detached” in the sense that modifying theHashSetwill not influence the map it was constructed from.However, if you modify an object inside the set (for example calling a setter on it), then those changes will be reflected inside the
HashMapas well (since theSetand theMapwill refer to the same object).One way around this is to make defensive copies of each element (using
clone()or by using a copy constructor).Another way is to use immutable objects.