java 例子分析
例子一 public class Test1 { public static void main(String[] args) { Map map = new HashMap(); List violateList = new ArrayList(); map.put("violateList", violateList); System.out.println(map); violateList = getList(); System.out.println(violateList); System.out.println(map); /** * 输出: * {violateList=[]} * [a, b, c, d] * {violateList=[]} * * 原因:map的key指向violateList变量,本质是指向了violateList变量对应的对象体; * violateList指向其他对象体时,不影响map的; 例子二可以证明 */ } public static List getList() { List list = new ArrayList(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); return list; } }
例子二 package test2016; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Test2 { public static void main(String[] args) { Map map = new HashMap(); List violateList = new ArrayList(); map.put("violateList", violateList); System.out.println(map); violateList.add("1"); violateList.add("2"); violateList.add("3"); violateList.add("4"); System.out.println(violateList); System.out.println(map); /** * 输出: * {violateList=[]} * [1, 2, 3, 4] * {violateList=[1, 2, 3, 4]} */ } }