1
  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?

ThisGuy
  • 833
  • 1
  • 9
  • 19

3 Answers3

7

It is simple.Use parametrized constructor

  HashMap<String,Integer> map2= new HashMap<String,Integer>(map);
Algorithmist
  • 6,657
  • 7
  • 35
  • 49
3

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.

LaurentG
  • 11,128
  • 9
  • 51
  • 66
1

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.

Community
  • 1
  • 1
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103