i want to clone a HashMap
which have a Object as value.
How does it works?
Asked
Active
Viewed 909 times
0

GETah
- 20,922
- 7
- 61
- 103

501 - not implemented
- 2,638
- 4
- 39
- 74
-
http://stackoverflow.com/questions/998376/clone-utility-for-hashmap-in-java – flesk Nov 20 '11 at 20:44
2 Answers
0
Do you mean something like:
public static <K, V extends MyObject>
HashMap<K, V> CloneHashMap (HashMap<K, V> input) {
HashMap<K, V> output = new HashMap<K, V>();
for(K key: input.keySet()) {
output.put(key, (V)(input.get(key).clone()));
}
return output;
}
where MyObject is a cloneable Object:
public class MyObject implements Cloneable {
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}

Tudor
- 61,523
- 12
- 102
- 142
0
It isn't clear what you are asking. Are you trying to clone the HashMap and all of its contents? Or do you simply want to create a copy of the Map?
If you simply want a copy of a Map you can use the copy constructor on HashMap.
HashMap copy = new HashMap(sourceMap);
This will create a second map with the same keys and value objects as the source map. If you want a deep clone, meaning you want new but equivalent objects you need to do something like what was suggested by @Tudor

Eric Rosenberg
- 1,543
- 9
- 18