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

Java ObjectInputStream读取文件到ArrayList传参后集合为空问题

问题原因

Java的方法参数传递是值传递:你调用readFile传入Pokemon.Pokedex时,实际是把该变量持有的集合引用的副本传给了方法形参newPokedex。
方法内执行newPokedex = (ArrayList<Pokemon>) readStream.readObject();时,只是修改了方法局部变量newPokedex的指向——让它指向反序列化生成的新集合对象,完全不会影响方法外部Pokemon.Pokedex的指向,外部变量依然指向调用方法前的空集合。这就是为什么方法内打印集合大小正常,方法外访问始终为空。

修正方案

两种常用实现方式二选一即可:

方案1:让方法直接返回读取到的集合(推荐)

修改readFile方法的返回值,不再通过形参传递集合,反序列化完成后直接返回结果,调用方手动给静态变量赋值即可。

// 方法签名改为返回ArrayList<Pokemon>
public static ArrayList<Pokemon> readFile(String fileName) {
    ArrayList<Pokemon> result = new ArrayList<>();
    // 用try-with-resources语法自动关闭流,避免异常场景下流泄漏
    try(
        FileInputStream readData = new FileInputStream(fileName);
        ObjectInputStream readStream = new ObjectInputStream(readData)
    ){
        result = (ArrayList<Pokemon>) readStream.readObject();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

对应main方法的调用写法调整为:

public static void main (String [] args) {
    // 直接接收方法返回的集合赋值给静态变量
    Pokemon.Pokedex = Pokemon.readFile("Pokedex.txt");
    System.out.println(Pokemon.Pokedex.size());
}

方案2:保留形参传参写法,操作原集合对象

如果要保留原来的传参逻辑,就不要给形参变量重新赋值,而是把反序列化得到的集合元素全部添加到传入的原集合中:

public static void readFile (String fileName, ArrayList<Pokemon> newPokedex) {
    try(
        FileInputStream readData = new FileInputStream(fileName);
        ObjectInputStream readStream = new ObjectInputStream(readData)
    ){
        ArrayList<Pokemon> readList = (ArrayList<Pokemon>) readStream.readObject();
        // 清空原集合旧数据,加入读取到的所有元素
        newPokedex.clear();
        newPokedex.addAll(readList);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这种写法下你原来的main方法调用逻辑不需要修改,就能得到正确结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.11 16:16:24