You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ArrayList存储HashMap时首个元素被覆盖 重复出现第二个元素问题咨询

问题根因

你当前的代码仅在循环外实例化了一次HashMap对象,Java中集合存储的是对象的引用而非对象本身的拷贝,你每次循环修改的都是同一个HashMap实例的内容,al2.add(map)只是把同一个实例的引用多次存入列表,最终列表中所有元素都指向同一个HashMap,所以展示的都是最后一次修改后的值。

修复方法

将HashMap的实例化操作移动到遍历行的循环内部,保证每一行数据对应一个独立的HashMap对象,修改后代码如下:

public static ArrayList<HashMap<String, String>> getAllData(){
        loadExcelFile();
        XSSFRow rowHeader=sheet.getRow(0);
        al=new ArrayList<Movie>();
        ArrayList<HashMap<String, String>> al2=new ArrayList<HashMap<String, String>>();
        int rowCount=sheet.getPhysicalNumberOfRows();
        for (int x=1; x<rowCount; x++) {
            // 每次循环新建独立的HashMap对象
            HashMap<String, String> map=new HashMap<String, String>();
            XSSFRow row=sheet.getRow(x);
            for (int y=0; y<row.getLastCellNum(); y++) {
                String key=rowHeader.getCell(y).getStringCellValue();
                String value=row.getCell(y).getStringCellValue();
                map.put(key, value);
            }
            al2.add(map);
        }
        System.out.println(al2);
        return al2;
    }

内容的提问来源于stack exchange,提问作者nikhil udgirkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 07:15:05