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
相关产品推荐
相关产品推荐

