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

Java数组指定索引无对应元素时如何将变量赋值为null

问题描述

现有Java逻辑遍历LinkedHashMap将键、值分别存入Keys、Values两个数组,访问索引为4的数组元素时,因数组实际长度仅为3,触发java.lang.ArrayIndexOutOfBoundsException数组索引越界异常。需要实现:数组不存在指定索引对应元素时不抛出异常,直接将role4、role4Alloc等对应变量赋值为null。
原有异常代码如下:

public class TEST {
    
    public static void main(String[] args) {
         String role1=null,role2=null,role3=null,role4=null,role5=null;
         String role1Alloc=null,role2Alloc=null,role3Alloc=null,role4Alloc=null,role5Alloc=null;
                
         LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();
         lhm.put("a", 6);
         lhm.put("b", 4);
         lhm.put("c", 7);
                
         String[] Keys = new String[lhm.size()];
         Integer[] Values = new Integer[lhm.size()];
         int i = 0;
         for (Map.Entry mapElement : lhm.entrySet()) {
             String key = (String) mapElement.getKey();
             int value = ((int) mapElement.getValue());
             Keys[i] = key;
             Values[i] = value;
             i++;
         }
                
         role4=Keys[4];// 触发越界异常
         role4Alloc=Values[4];// 触发越界异常
    }
}
异常原因
  • 数组初始化时长度和Map实际元素个数一致,示例中Map仅存入3个元素,因此数组长度为3,合法索引范围是0、1、2,不存在索引4的位置
  • Java原生数组不支持超范围访问自动返回null,直接访问超出长度的索引必然抛出ArrayIndexOutOfBoundsException
解决方法

核心逻辑是访问数组元素前先做边界校验:判断要访问的索引是否在合法区间内,满足条件则取对应位置的值,否则直接赋值null,即可避免抛出异常。
替换原有触发越界的两行赋值代码即可:

// 数组索引从0开始,要访问索引4的元素,需要数组长度大于4
role4 = Keys.length > 4 ? Keys[4] : null;
role4Alloc = Values.length > 4 ? Values[4] : null;

如果需要给role1~role5及对应的Alloc变量全部赋值,可按相同规则统一处理(以下示例按存入顺序第1个元素对应role1、索引为0的规则编写,可根据实际索引对应关系调整):

role1 = Keys.length > 0 ? Keys[0] : null;
role1Alloc = Values.length > 0 ? Values[0] : null;
role2 = Keys.length > 1 ? Keys[1] : null;
role2Alloc = Values.length > 1 ? Values[1] : null;
role3 = Keys.length > 2 ? Keys[2] : null;
role3Alloc = Values.length > 2 ? Values[2] : null;
role4 = Keys.length > 3 ? Keys[3] : null;
role4Alloc = Values.length > 3 ? Values[3] : null;
role5 = Keys.length > 4 ? Keys[4] : null;
role5Alloc = Values.length > 4 ? Values[4] : null;

注意:数组的合法索引范围固定为0到数组长度-1,所有数组下标访问场景都建议先做边界判断,从根源上避免越界异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 19:15:41