解决Java循环中使用Map时在put值时value值被覆盖的问题

332 阅读1分钟

实际项目遇到Map在put值value值被覆盖,经过dubug打断点发现,每次put的值被前一个值覆盖掉。

 Map<String, Object> targetmap = null;
            List<Map<String, Object>> finalTag = new ArrayList<>();
            for (Map.Entry<String, Object> map : commentKeyToCamel.entrySet()) {
                Object sourceKey = map.getKey();
                System.out.println("sourceKey" + sourceKey);
                //判断结果集中是否包含key
                if (mapTypes.containsKey(sourceKey)){
                    mapTypes.put((String)commentKeyToCamel.get(sourceKey),mapTypes.get(sourceKey));
                    System.out.println("键===" + commentKeyToCamel.get(sourceKey) + "值===" + mapTypes.get(sourceKey));
                    targetmap = new HashMap<String,Object>();
                    targetmap.put((String)commentKeyToCamel.get(sourceKey),mapTypes.get(sourceKey));
                    finalTag.add(targetmap);
                }
                System.out.println("最新的结果:" + finalTag);
            }

解决思路: 前一天下班之后还一直找错误,第二天debug代码一步一步查找参数值时,发现每次put的都是最新的数据,这时发现代码问题了,于是上网搜索有没有类似的问题,结果还真有,网上解决办法是这样的: 只需要把容器换成list,见以下代码:

@RequestMapping("controller/json/AssetsController/getAssetsInfosysAndType")
    @ResponseBody
    public Msg getAssetsInfosysAndType() {
        List list = new ArrayList();
        List<AssetsInfosys> assetsInfoSysServiceAll = assetsInfoSysService.getAll();
        List<AssetsStructureLowerMenu> lowerMenuServiceAll = assetsStructureLowerMenuService.getAll();
        for (AssetsInfosys ai :
                assetsInfoSysServiceAll) {
            for (AssetsStructureLowerMenu lmsa :
                    lowerMenuServiceAll) {
                if (ai.getName().equals(lmsa.getSuperiormenu())) {
                    Map map = new HashMap();
                    map.put("assetsInfoSys", ai);
                    map.put("msgAssetsType", lmsa);
                    list.add(map);
                }
            }
        }
        return Msg.success().add("AllMsgAssetsInfosysAndType", list);
    }

阅读《干法》~持续就是力量

参考: www.cnblogs.com/kinome/p/96…