对象变化影响map中的数据

public static void main(String[] args) {
        Person p = new Person("tom","15");
        Map<String,Person> map2 = new HashMap<>();
        Map<String,Person> map3 = new HashMap<>();
        map2.put("m2", p);
        map3.put("m3", p);
        p.setName("jerry");
        System.out.println(map2.get("m2"));
        System.out.println(map3.get("m3"));
    }

如上代码,类Person有两个属性,name和age,在放到map后,如果改变其中一个属性的值,map中已经存放进去的数据会受到影响.

    public static void main(String[] args) {
        String p = "a";
        Map<String,String> map2 = new HashMap<>();
        Map<String,String> map3 = new HashMap<>();
        map2.put("m2", p);
        map3.put("m3", p);
        p = "ss";
        System.out.println(map2.get("m2"));
        System.out.println(map3.get("m3"));
    }

但是如果放进去的不是个普通对象,String或者基本类型封装类,那么就不会受到影响.

原因初步理解:

  当集合List(Set or HashMap )中放一个对象时,其实是放了引用,在get这个数据时,是通过引用获得这个对象,如果get之前这个对象中的属性被改了,那么再拿到的数据就会发生改变.

  当集合中放到是基本类型时,包含特殊对象String,放到集合中,改动后的数据直接放在里面了,就不会被改变.再次拿到时还是改变之前的值.

原文地址:https://www.cnblogs.com/havenenjoy/p/4684209.html