证明,我先构造了一个很大的List对象,用VisualVM查看的内存一下变大了,然后我for循环向map放进了100个之前的list,如果存的是对象,那内存会暴增,但是内存没有变化,证明map存的是引用,下面证明两个对象不一致,但是存进map后,对比两个对象为true的只能为引用
@Data @Accessors(chain = true) public class Person { private String name; private Integer age; }
package com.netty.demos; import com.netty.demos.client.entiy.Person; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<Integer, Person> mapA = new HashMap<Integer, Person>(); Map<String, Person> mapB = new HashMap<String, Person>(); Person per = new Person(); Person per2 = new Person(); Person per3 = new Person(); per.setName("x"); System.out.println("per "+per.toString()); per2=per; System.out.println("per2 "+per2.toString()); mapA.put(1, per2); per.setName("y"); System.out.println("per "+per.toString()); per3=per; System.out.println("per3 "+per3.toString()); mapB.put("1", per3); System.out.println(per2==per3); System.out.println(mapA.get(1).equals(mapB.get("1"))); } }
编辑