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

Java HashMap循环插入时所有条目被覆盖为最后插入值问题求助

问题原因

你在循环外仅创建了一个Element对象实例,HashMap存储对象时保存的是对象的内存引用而非对象副本。后续每次循环都是修改这同一个Element的属性,导致HashMap中所有键对应的引用指向的都是这个被反复覆盖的对象,因此每次插入新元素后,所有条目都会显示为最新插入的内容。

修复方案

将Element的实例化逻辑移动到循环内部,每次处理新行数据时创建独立的Element对象即可,核心修改后的代码如下:

public class main {
public static void main(String[] args) throws FileNotFoundException {
    
    Map<Integer, Element> map_football = new HashMap<>(); 
    Map<Integer, Element> map_weather = new HashMap<>();  
    
    // 移除循环外的Element实例化代码
    BufferedReader br = null;
    String myFile="weather.dat";
    
            try {
                File file = new File(myFile);
                Scanner scanner = new Scanner(file);
                scanner.nextLine();
                while(scanner.hasNextLine()){
                    
                    try{
                        // 每次循环创建独立的Element实例
                        Element element= new Element();
                        Integer Dy=scanner.nextInt();
                        Integer MxT = scanner.nextInt();
                        Integer MnT = scanner.nextInt();
                        
                        Integer exc=MxT-MnT;
                        
                        element.setDy(Dy);
                        element.setExc(exc);
                        
                        System.out.println(element.toString());
                        map_weather.put(exc, element);
                        
                        map_weather.forEach((key, value) -> System.out.println(key + ":" + value));
                        System.out.println("New Cycle\n");
                        scanner.nextLine();
                    }catch(InputMismatchException ex){
                        scanner.nextLine();
                    }
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            finally {
                if (br != null) {
                    try {
                        br.close();
                    }
                    catch (Exception e) {
                    };
                }
            }       

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:42:00