4

What is the best of cloning a LinkedHasMap in Java?

I already tried:

Map<String, Object> clonedMap = new LinkedHashMap<String, Object>(originalMap);

But that didn't work.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
RedEagle
  • 4,418
  • 9
  • 41
  • 64
  • Why didn't it work? What do you want it to do? – SLaks Dec 21 '11 at 01:59
  • 7
    Define "didn't work". `new Map(map)` makes a "shallow" copy - the references are the same. If you mean a "deep" copy (where all keys and values are *also* cloned) the answer depends entirely on the implementation of the the key and value classes. – Bohemian Dec 21 '11 at 02:00
  • 1
    As Bohemian has said, deep copy is likely what you are after. See [here](http://stackoverflow.com/questions/64036/how-do-you-make-a-deep-copy-of-an-object-in-java). – threenplusone Dec 21 '11 at 02:03

1 Answers1

1

The easiest way to get a deep copy is to serialize the map and then deserialize it. The faster way is to go thought the whole map, clone each key/value and put it to a new map.

In case you need a shallow copy - your snippet does that correctly.

Alexey Grigorev
  • 2,415
  • 28
  • 47
  • Although serialization is a simple solution, if you want something automatic, I'd rather use reflection. But even better is to have all your cloneable classes implement the Cloneable interface (http://docs.oracle.com/javase/6/docs/api/java/lang/Cloneable.html). – Ravi Wallau Dec 21 '11 at 02:52