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

JavaFX 17程序触发java.lang.OutOfMemoryError问题求助

问题原因分析

你的代码触发java.lang.OutOfMemoryError的核心原因是无限循环:当处理到字符串最后一个数字时,循环变量会被重置为0,导致程序不断重复添加同一个元素到LinkedList,最终耗尽堆内存。

具体逻辑漏洞:

  1. 当处理到最后一个数字时,strInput.indexOf(" ", x)返回-1(找不到后续空格)
  2. 提取最后一个数字并添加到列表后,循环变量x被赋值为emptySpace + 1,也就是0
  3. 循环条件x < endString依然成立,程序重新开始循环,重复执行上述步骤,无限往列表中插入元素
修复方案

方案1:修正循环逻辑

处理完最后一个元素后直接终止循环,避免无限迭代:

LinkedList<Integer> inputList = new LinkedList<>();

public void stringToInteger(String strInput) {
    int emptySpace = 0;
    int endString = strInput.length();
    String str;

    for(int x=0; x<endString; x = emptySpace + 1) {
        emptySpace = strInput.indexOf(" ", x);

        if (emptySpace != -1) {
            str = strInput.substring(x, emptySpace);
            inputList.add(Integer.parseInt(str.trim()));
        } else {
            str = strInput.substring(x);
            inputList.add(Integer.parseInt(str.trim()));
            break; // 新增break,终止循环
        }
    }
}

方案2:使用字符串拆分API(推荐)

利用Java原生的split()方法简化逻辑,同时兼容连续空格、首尾空格等场景:

LinkedList<Integer> inputList = new LinkedList<>();

public void stringToInteger(String strInput) {
    // 按任意空白字符拆分(支持多个连续空格、制表符等)
    String[] numStrings = strInput.split("\\s+");
    for (String s : numStrings) {
        if (!s.isEmpty()) { // 跳过拆分后产生的空字符串
            inputList.add(Integer.parseInt(s));
        }
    }
}

主函数修正

注意非静态方法不能直接在静态main方法中调用,需先创建类实例:

public static void main(String[] args) {
    ExampleClass instance = new ExampleClass();
    String testHeap = "5 6 1 7 12 21 58";
    instance.stringToInteger(testHeap);
    System.out.println(instance.inputList);
}
额外优化建议
  • 方法名遵循Java驼峰命名规范:将StringtoInteger改为stringToInteger
  • 若输入字符串可能包含非数字内容,建议添加NumberFormatException异常捕获,避免程序直接崩溃
  • 若处理超大量数据,可考虑使用ArrayList替代LinkedList,提升插入和访问性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:05:14