list,map的疑问
代码:
package com.wyl; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class aaa { public static void main(String[] args) { // location 1 List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); Map<String,Object> map = new HashMap<String,Object>(); String a = "23"; System.out.println(a); for(int i=0;i<10;i++){ //location 2 // Map<String,Object> map = new HashMap<String,Object>(); map.put("age", "xiaoming:"+i); System.out.println("=========:"+i); list.add(map); } Iterator it = list.iterator(); while(it.hasNext()){ Map m = (Map)it.next(); String age = (String) m.get("age"); System.out.println("age:"+age); } } }
分别在location1和location2出实例化出map,打印出来的数值就是不一样。
问题应该处在list上:
下面是一个list的Demo:
package com.wyl; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class listDemo { public static void main(String[] args) { List list = new ArrayList<String>(); Map map = new HashMap<String, Object>(); map.put("age", 234); map.put("name", "小明"); list.add(map); Iterator it2 = list.iterator(); while(it2.hasNext()){ System.out.println("the first:"+it2.next()); } System.out.println("======================"+list.size()); map.put("we", "wyl"); list.add(map); System.out.println("list.size:"+list.size()); Iterator it = list.iterator(); while(it.hasNext()){ System.out.println("the next:"+it.next());//诡异的的事情发生了 } System.out.println(map.size()); } }
打印结果:
the first:{name=小明, age=234} ======================1 list.size:2 the next:{name=小明, age=234, we=wyl} the next:{name=小明, age=234, we=wyl} 3
自己多试了几遍,应该跟Java的值传递相关的基础知识有关,下面是listDemo02:
package com.wyl; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class listDemo2 { public static void main(String[] args) { Map<String,Object> map = new HashMap<String,Object>(); List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); map.put("name", "夏末"); map.put("age", 26); list.add(map); Iterator it = list.iterator(); while(it.hasNext()){ System.out.println("the first:"+it.next()+"====");//诡异的的事情发生了 } map.put("age", 30);//修改年岁 Iterator it2 = list.iterator();//迭代出list的内容 if(it2.hasNext()){ System.out.println("the next :"+it2.next());//这个跟Java的值传递有关 System.out.println("list的size():"+list.size()); }else{ System.out.println("=========="); } } }
打印结果:
the first:{age=26, name=夏末}==== the next :{age=30, name=夏末} list的size():1