7

Is there java utility that does clone() method for HashMap such that it does copy of the map elements not just the map object (as the clone() in HashMap class)?

sigod
  • 3,514
  • 2
  • 21
  • 44
Moro
  • 2,088
  • 6
  • 25
  • 34

5 Answers5

12

What about other objects referred to in the elements? How deep do you want your clone?

If your map elements don't have any deep references and/or everything is Serializable, you can serialize the map via ObjectOutputStream into a ByteArrayOutputStream and then deserialize it right away.

The only other alternative is to do it manually.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
1

The SO question Deep clone utility recommendation is similar to this one, and has an answer that may be helpful to you.

To summarize, they recommend using the Cloning library from Google Code. From personal experience, it deep-copies HashMaps. It can even clone things that aren't Cloneable.

Community
  • 1
  • 1
Ian Durkan
  • 1,212
  • 1
  • 12
  • 26
1

Once you know your key/value pair elements are cloneable:

HashMap<Foo, Bar> map1 = populateHashmap();
HashMap<Foo, Bar> map2 = new HashMap<Foo, Bar>();

Set<Entry<Foo, Bar>> set1 = map1.entrySet();
for (Entry<Foo, Bar> e : l)
    map2.put(e.getKey().clone(), e.getValue().clone());
sigod
  • 3,514
  • 2
  • 21
  • 44
Oso
  • 528
  • 4
  • 18
  • 2
    @Oso: What happens if e.getKey() or e.getValue() is another HashMap() or other object that also requires a deep-copy clone? – Grant Wagner Jun 15 '09 at 21:18
  • well... this is a simple hashmap clone routine. I am actually assuming that the objects are cloneable, so the deepnes will be solved by the key/value objects themselves. In order to deepclone a hashmap without assuming serializable/cloneable, I think reflection would be a way (still not sure if true). – Oso Jun 16 '09 at 14:40
0

Often copy should be deep. Here is an example how to "deep copy"

Map<Integer, ArrayList<Integer>>

code:

public static Map<Integer, ArrayList<Integer>> deepCopyMapIntList
        (Map<Integer, ArrayList<Integer>> original) {

    Map<Integer, ArrayList<Integer>> copy = new HashMap<>(original.size());

    for (int i : original.keySet()) {
        ArrayList<Integer> list = original.get(i);

        copy.put(i, (ArrayList<Integer>) list.clone());
    }
    return copy;
}
Andrew
  • 36,676
  • 11
  • 141
  • 113
0

Take a look at the deepClone method at http://www.devdaily.com/java/jwarehouse/netbeans-src/db/libsrc/org/netbeans/lib/ddl/impl/SpecificationFactory.java.shtml . It is not generic, but it includes several built-in types (including HashMap itself, recursively), and can obviously be extended.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539