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

Android应用购买导弹时触发IndexOutOfBoundsException崩溃问题

问题分析与修复方案

崩溃原因

报错java.lang.IndexOutOfBoundsException: Index: 5, Size: 3的核心问题是LinkedList方法重载引发的调用歧义:

  • LinkedList提供两个remove方法:remove(int index)(按索引删除元素)和remove(Object o)(按元素值删除)
  • 代码中lMissile是int类型,调用MissilePreferences.remove(lMissile)时,Java会优先匹配remove(int index)方法,而非预期的按值删除方法
  • 当lMissile的数值大于等于列表当前长度(比如列表仅3个元素,lMissile为5),就会触发索引越界异常

修复方案

明确调用按值删除的remove(Object)方法,将int类型的lMissile包装为Integer对象,引导Java匹配正确的重载方法:

修改后的代码:

public static void SetMissilePreferred(int lMissile) {
    // Set a purchased missile to go to the top of the preferred list.
    if (MissilePreferences == null)
        MissilePreferences = new LinkedList<>();

    Integer missile = Integer.valueOf(lMissile);
    if (MissilePreferences.contains(missile))
        MissilePreferences.remove(missile); // 明确调用按对象移除的方法

    MissilePreferences.push(lMissile);

    if (MissilePreferences.size() > PREFERENCE_LIST_SIZE)
        MissilePreferences.removeLast();
}

额外优化建议

  • 把PREFERENCE_LIST_SIZE定义为静态常量(比如private static final int PREFERENCE_LIST_SIZE = 3;),避免使用魔法数值
  • 如果该方法会被多线程调用,需给MissilePreferences的操作逻辑加锁(比如synchronized块),保证线程安全

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:48:35