Map<String, Object> map = new HashMap<String, Object>(existMap)解析

HashMap初始化

使用

Map<String, Object> map = new HashMap<String, Object>(existMap);

得到的新map与原existMap的联系。

实验代码


/**
 * HashMap使用new HashMap<>(map)复制另一个map时,为浅复制,生成了另一块空间,
 * 但新map中引用的对象仍与原map相同,修改引用对象中的值,两个map均会发生变化。
 */
package com.chang.finalabout;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class FinalAbout {

    public static void main(String[] args) {
        final String str = "abc";
        final Map<String, A> map = new HashMap<String, A>();

        map.put("1", new A("1"));
        map.put("2", new A("2"));
        map.put("3", new A("3"));
        Map<String, A> mapcopy = new HashMap<String, A>(map);

        System.out.println("Original map:");
        for(Entry<String, A> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "-" + entry.getValue().a);
        }

        System.out.println("Copy map:");
        for(Entry<String, A> entry : mapcopy.entrySet()) {
            System.out.println(entry.getKey() + "-" + entry.getValue().a);
        }

        mapcopy.put("7", new A("7"));
        mapcopy.put("8", new A("8"));

        mapcopy.get("1").Aa("1111111");
        mapcopy.get("2").Aa("2222222");
        mapcopy.put("2", new A("000"));
        mapcopy.remove("3");

        System.out.println("after copy and modified, the Original map:");
        for(Entry<String, A> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "-" + entry.getValue().a);
        }

        System.out.println("after modified, the Copy map:");
        for(Entry<String, A> entry : mapcopy.entrySet()) {
            System.out.println(entry.getKey() + "-" + entry.getValue().a);
        }

    }

}

class A {
    public String a = new String();

    public A(String a) {
        this.a = a;
    }

    public void Aa(String a) {
        this.a = a;
    }

}

Console输出:


Copy map:
1-1
2-2
3-3
after copy and modified, the Original map:
1-1111111
2-2222222
3-3
after modified, the Copy map:
8-8
1-1111111
2-000
7-7

分析

新mapcopy与原map的内容一致;对新mapcopy的增加,删除操作对原map无任何影响,但修该新mapcopy中object元素也会对原map造成影响。
可以得出:新mapcopy开辟了一块新的内存单元,但map中Object类型的元素并没有开辟新内存,依旧是原map中Object内存地址的引用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值