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

Java多层Map嵌套存储选举得票数据时元素添加异常问题

问题根因

你全程仅创建了1个Map<Integer, Double> helpMap实例,外层Map存储的是该实例的内存引用,每次循环调用helpMap.clear()修改的都是同一块内存空间的数据,最终外层Map中所有政党名称对应的value都会变为最后一次循环处理的政党数据。

修复方案

将内层Map的实例化逻辑移动到循环内部,每次处理一个政党数据时都新建独立的内层Map即可,修改后的核心代码如下:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class MainMethod extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        Map <String, Map <Integer, Double>> parties = new LinkedHashMap <>();
        String filename = "C://Users//rares//IdeaProjects//DataVizualization//src//main//java//partiesdata.tsv";
        File file = new File(filename);
        Scanner inputFile = new Scanner(file);
        Integer c = 0;
        Integer year;
        while (inputFile.hasNext()) {
            String partySupport = inputFile.nextLine();
            // 用正则匹配多空白符拆分,避免制表符/空格数量不对导致拆分失败
            String[] split = partySupport.split("\\s+");
            c++;
            if (c > 1) {
                // 每次处理新政党时新建独立的内层Map
                Map <Integer, Double> helpMap = new LinkedHashMap <>();
                year = 1964;
                for (int i = 1; i < split.length; i++) {
                    year = year + 4;
                    if (!split[i].equals("-")) {
                        helpMap.put(year, Double.valueOf(split[i]));
                    }
                }
                parties.put(split[0], helpMap);
                System.out.println(helpMap);
            }
        }
        inputFile.close();
        System.out.println(parties);

        NumberAxis xAxis = new NumberAxis(1968, 2008, 4);
        NumberAxis yAxis = new NumberAxis(0, 30, 4);
        LineChart <Number, Number> lineChart = new LineChart <> (xAxis, yAxis);
        lineChart.setTitle("Relative support of the parties");

        parties.keySet().forEach(party -> {
            XYChart.Series data = new XYChart.Series();
            data.setName(party);
            parties.get(party).entrySet().forEach(pair -> {
                data.getData().add(new XYChart.Data(pair.getKey(), pair.getValue()));
            });
            lineChart.getData().add(data);
        });

        Scene view = new Scene(lineChart, 640, 480);
        stage.setScene(view);
        stage.show();
    }
}

其他优化建议

  • 类名遵循Java大驼峰命名规范,将mainMethod修改为MainMethod更符合代码规范
  • 读取文件建议使用try-with-resources语法自动关闭流,避免资源泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:06:03