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

Java数组无法正确存储Insurance对象引用,空指针异常求助

解决数组空指针问题的几种方案

你的问题根源很明确:创建了长度为5的Insurance数组,但只给前3个位置赋值了对象,剩下的2个元素默认是null。遍历整个数组时,调用null对象的displayInfo()方法自然会触发空指针异常。下面是几种可行的解决办法:

方法1:遍历前先判断元素非空

遍历数组时,先检查当前元素是否为null,只有非空时才调用方法。这是最直接的修复方式,不需要改动数组结构:

// 遍历数组的代码
for (Insurance insurance : yourInsuranceArray) {
    if (insurance != null) { // 增加非空判断
        insurance.displayInfo();
    }
}

方法2:只遍历已赋值的元素

如果你确定只赋值了3个元素,可以直接遍历前3个位置,避免触碰null元素:

// 循环次数改为实际赋值的数量(3次)
for (int i = 0; i < 3; i++) {
    yourInsuranceArray[i].displayInfo();
}

方法3:改用动态集合ArrayList

如果你的保险对象数量不固定,推荐放弃固定长度的数组,改用ArrayList<Insurance>,它会自动扩容,不会存在未赋值的null元素:

// 初始化动态集合
ArrayList<Insurance> insuranceList = new ArrayList<>();

// 循环3次添加对象
for (int i = 0; i < 3; i++) {
    // 获取用户输入,创建Auto对象
    Auto autoInsurance = new Auto(typeInput, costInput);
    insuranceList.add(autoInsurance);
}

// 遍历集合,无需担心null
for (Insurance insurance : insuranceList) {
    insurance.displayInfo();
}

额外提醒:静态变量的问题

顺便提一句,你在抽象父类Insurance里定义了typeOfInsurance和monthlyCost为静态变量,这意味着所有子类实例会共享这两个值,可能不符合保险对象各自有类型和月费的需求。建议把它们改成非静态成员变量,每个对象独立持有自己的属性值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:55:22