Reputation: 873
HashMap<String,Integer> map= new HashMap<String,Integer>();
map.put("first",1);
map.put("second",2);
map.put("third",3);
HashMap<String,Integer> map2= new HashMap<String,Integer>();
map2= map.clone();
My question is how do I transfer items from map to map2? Is my code right?
Upvotes: 1
Views: 827
Reputation: 41200
If you are looking deep copy of your previous map use copy constructor, clone is a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
If you want shallow copy of your previous map you could use pass the map reference to your new map constructor
rather than clone
method.
HashMap<String,Integer> map2= new HashMap<>(map);
There are annoyance over clone method find SO.
Josh Bloch on Design - Copy Constructor versus Cloning
If you've read the item about cloning in my book, especially if you read between the lines, you will know that I think clone is deeply broken. [...] It's a shame that Cloneable is broken, but it happens.
Upvotes: 1
Reputation: 11757
You could do this:
HashMap<String,Integer> map2= new HashMap<String,Integer>();
map2.putAll(map);
or
HashMap<String,Integer> map2= new HashMap<String,Integer>(map);
Note that in both methods, the keys and values are not duplicated but just referenced by both HashMap
.
Upvotes: 3
Reputation: 6695
It is simple.Use parametrized constructor
HashMap<String,Integer> map2= new HashMap<String,Integer>(map);
Upvotes: 7