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

Java读取文本文件数据存入ArrayList后所有元素均为最后一条问题排查

你遇到的问题和ArrayList无关,是Question类的成员变量使用了static修饰导致的。

static修饰的成员变量属于类本身,所有该类的实例会共享同一份变量值。你在循环中每次新建Question对象时,给static变量赋值都会覆盖上一次的赋值结果,所以循环结束后所有Question实例读取到的都是最后一次赋值的内容。
你在循环内打印的是刚添加的新对象的属性,此时static变量刚被赋值为当前题目的内容,所以打印结果看起来是正常的。

解决方法

打开Question类的定义,删除成员变量前的static修饰符,将其改为普通实例变量即可。如果要避免外部数组修改影响Question内部存储的选项,构造方法中可以额外做一次数组拷贝。

错误代码示例(Question类):

public class Question {
    // 错误:static修饰导致所有实例共享值
    private static String inquiry;
    private static String[] responses;
    private static String fact;

    public Question(String inquiry, String[] responses, String fact) {
        this.inquiry = inquiry;
        this.responses = responses;
        this.fact = fact;
    }
    // 省略get/set方法
}

正确代码示例:

import java.util.Arrays;

public class Question {
    // 正确:去掉static,每个实例单独持有属性
    private String inquiry;
    private String[] responses;
    private String fact;

    public Question(String inquiry, String[] responses, String fact) {
        this.inquiry = inquiry;
        // 可选:数组拷贝避免外部修改影响内部数据
        this.responses = Arrays.copyOf(responses, responses.length);
        this.fact = fact;
    }
    // 省略get/set方法
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:24:09