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.

3
  • Why didn't it work? What do you want it to do? Commented Dec 21, 2011 at 1: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. Commented Dec 21, 2011 at 2:00
  • 1
    As Bohemian has said, deep copy is likely what you are after. See here. Commented Dec 21, 2011 at 2:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 (docs.oracle.com/javase/6/docs/api/java/lang/Cloneable.html).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.