map复制 java,如何在Java中复制HashMap(不是浅拷贝)

I need to make a copy of HashMap > but when I change something in the copy I want the original to stay the same. i.e when I remove something from the List from the copy it stays in the List in the original.

If I understand it correctly, these two methods create just shallow copy which is not what I want:

mapCopy = new HashMap<>(originalMap);

mapCopy = (HashMap) originalMap.clone();

Am I right?

Is there a better way to do it than just iterate through all the keys and all the list items and copy it manually?

解决方案

You're right that a shallow copy won't meet your requirements. It will have copies of the Lists from your original map, but those Lists will refer to the same List objects, so that a modification to a List from one HashMap will appear in the corresponding List from the other HashMap.

There is no deep copying supplied for a HashMap in Java, so you will still have to loop through all of the entries and put them in the new HashMap. But you should also make a copy of the List each time also. Something like this:

public static HashMap> copy(

HashMap> original)

{

HashMap> copy = new HashMap>();

for (Map.Entry> entry : original.entrySet())

{

copy.put(entry.getKey(),

// Or whatever List implementation you'd like here.

new ArrayList(entry.getValue()));

}

return copy;

}

If you want to modify your individual MySpecialClass objects, and have the changes not be reflected in the Lists of your copied HashMap, then you will need to make new copies of them too.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值