map在list循环里面赋值问题

查询回一个List>集合,for循环里面遍历这个集合给新的list复制判断到特定的条件给这个list添加map
结果,List集合中的所有当前map都被处理了,各种new对象,都未解决;

问题原因是:指向问题:修改对象指向的是一个对象地址

解决办法:循环list时,将对象每次都克隆一次,putAll();

List> allCountList = new ArrayList>();
Map objectMap = new HashMap();
objectMap.put(“weizhi”, “”);
objectMap.put(“dw”, “艾欧尼亚”);
objectMap.put(“renshu”, “”);
allCountList.add(objectMap);
// Map objectMap1 = new HashMap();
// objectMap1.put(“dydj”, “”);
// objectMap1.put(“dw”, “昌吉”);
// objectMap1.put(“bdzsl”, “”);
// allCountList.add(objectMap1);
List> newAllCountList = new ArrayList>();
// for (Map objectMap2 : allCountList
// ) {
Map objectMap1 = allCountList.get(0);
if (objectMap1.get(“weizhi”).toString().equals("")) {
Map objectMap2 = objectMap1;
Map objectMap3 = objectMap1;
objectMap1.put(“weizhi”, “sup”);
objectMap1.put(“renshu”, 15);
newAllCountList.add(objectMap1);
System.out.println(“1-------” + newAllCountList);
// Map objectMap1 = objectMap2;
objectMap2.put(“weizhi”, “ad”);
objectMap2.put(“renshu”, 53);
newAllCountList.add(objectMap2);
System.out.println(“2-------” + newAllCountList);
objectMap3.put(“weizhi”, “mid”);
objectMap3.put(“renshu”, 20);
newAllCountList.add(objectMap2);
System.out.println(“3-------” + newAllCountList);
} else {
newAllCountList.add(objectMap1);
}

原先这样的代码输出为
[{weizhi=mid, dw=艾欧尼亚, renshu=20}, {weizhi=mid, dw=艾欧尼亚, renshu=20}, {weizhi=mid, dw=艾欧尼亚, renshu=20}]
需要改为

List> allCountList = new ArrayList>();
Map objectMap = new HashMap();
objectMap.put(“weizhi”, “”);
objectMap.put(“dw”, “艾欧尼亚”);
objectMap.put(“renshu”, “”);
allCountList.add(objectMap);
// Map objectMap1 = new HashMap();
// objectMap1.put(“dydj”, “”);
// objectMap1.put(“dw”, “昌吉”);
// objectMap1.put(“bdzsl”, “”);
// allCountList.add(objectMap1);
List> newAllCountList = new ArrayList>();
// for (Map objectMap2 : allCountList
// ) {
Map objectMap1 = allCountList.get(0);
if (objectMap1.get(“weizhi”).toString().equals("")) {
Map objectMap2 = new HashMap();
objectMap2.putAll(objectMap1);//这行代码解决指向问题
Map objectMap3 = new HashMap();
objectMap3.putAll(objectMap1);
objectMap1.put(“weizhi”, “sup”);
objectMap1.put(“renshu”, 15);
newAllCountList.add(objectMap1);
System.out.println(“1-------” + newAllCountList);
// Map objectMap1 = objectMap2;
objectMap2.put(“weizhi”, “ad”);
objectMap2.put(“renshu”, 53);
newAllCountList.add(objectMap2);
System.out.println(“2-------” + newAllCountList);
objectMap3.put(“weizhi”, “mid”);
objectMap3.put(“renshu”, 20);
newAllCountList.add(objectMap2);
System.out.println(“3-------” + newAllCountList);
} else {
newAllCountList.add(objectMap1);
}

输出为
[{weizhi=sup, dw=艾欧尼亚, renshu=15}, {weizhi=ad, dw=艾欧尼亚, renshu=53}, {weizhi=ad, dw=艾欧尼亚, renshu=53}]

解决0.0

你可能感兴趣的:(java)