解決 java循環中使用 Map時 在put值時value值被覆蓋的問題


 

其實很簡單,只需要把容器換成list

然后在循環中,每次循環末尾map = new HashMap() 或者直接在循環中一開始就實例化hashmap(Map map = new HashMap();),這樣就不會造成map覆蓋了。

注:Map map = new HashMap(); 如果是在循環場景下使用,則必須在循環中以局部實例化的方式出現,見示例2 fetchAssetsList 方法。

 

    @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);
    }

 

示例2:(fetchAssetsList方法)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM