开发者

How do you clone elements in a Map

private static Map<Integer, String> choices = new HashMap<Integer, String>(3);
// choices get populated here

What is the simplest way开发者_StackOverflow to clone elements in a Map to a different structure.


For your case, since Integers and Strings are immutable, you can do what Mark said. This works because you can not modify the Integers/Strings once they are created.

In the general case though, where you do not have immutable object, you need to understand very clearly what you are trying to do. There are two possibilities, and each will have drastically different consequences.

The first is that you want to create a new Map that contains equivalent references to the objects in the first Map. If you go this route, both Maps will contain references that point to the same underlying objects. i.e. if you pull an object out of either Map and modify it, the change will be reflected in the other collection, because both Maps contain references to the same objects. If you want to go this route, @Mark provided a good answer.

The second is that you want to create a new Map that contains references to copies of the objects in the first Map. In this case, you actually need to create a new Object for every Object in the first Map. You can add a copy() method to the class definitions, or you can create a 'copy constructor' on the class. This is a constructor that takes a reference to an Object of its type and creates a duplicate of the argument. Since you are copying the objects themselves, then modifying the object in a Map will not affect the objects in the other Map. Note that if your objects in turn have references to other objects, you need to copy those too.

These choices exist because in Java, when you do Object obj = new Object(), 'obj' is a reference to the thing you just created. If you then do Object obj2 = obj you have 2 references to the same underlying Object. Invoking methods or changing properties on either reference affects the same object.

When you go with the first approach, you end up with different references in each map (because java is always pass by value, which means that the reference values are copied), but those different references still have the same value, so they point to the same underlying object.


By your use of "clone" I assume you're trying to copy the elements to another map. You can do that easily:

Map<...> myMap;

Map<...> newMap = new HashMap<...>(myMap);

//or

Map<...> newMap;
newMap.putAll(myMap);


It depends on how deep you want to clone. If your keys and values are serializable then you can deserialize and serialize again. Otherwise, the alternative is to do manually.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜