ThisGuy
ThisGuy

Reputation: 873

how to transfer contents from previous hashmap to a new hashmap?

  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

Answers (3)

Subhrajyoti Majumder
Subhrajyoti Majumder

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

LaurentG
LaurentG

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

Algorithmist
Algorithmist

Reputation: 6695

It is simple.Use parametrized constructor

  HashMap<String,Integer> map2= new HashMap<String,Integer>(map);

Upvotes: 7

Related Questions