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

Java ArrayList首个元素始终为null问题排查求助

问题:ArrayList首个元素调用getProduct(0)返回null的原因及修复方案

问题根源

你的代码里Store类的getProduct方法存在逻辑错误,导致传入索引0时直接返回null,而非ArrayList中实际存在的元素。

原方法代码:

public Product getProduct(int index) {
    if ((index > 0) && (index < products.size())) return products.get(index);
    return null;
}

这里的条件index > 0错误排除了索引0的情况——ArrayList索引从0开始,0是合法的有效索引,却被直接判定为无效并返回null。

修复后的getProduct方法

修改判断条件,将index > 0改为index >= 0,即可正确返回包括0号索引在内的所有有效元素:

public Product getProduct(int index) {
    if ((index >= 0) && (index < products.size())) {
        return products.get(index);
    }
    return null;
}

额外注意事项

  • equals方法不符合约定:当前Product类的equals仅比较价格,这会导致getProductIndex方法可能返回错误索引。建议按对象唯一标识(比如id)重写equals和hashCode:

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Product product = (Product) o;
        return Objects.equals(id, product.id);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
    

    (需导入java.util.Objects)

  • 循环大括号缺失:main方法末尾的外层for循环缺少大括号,导致后续代码逻辑错误,应补充大括号包裹所有循环体内容:

    for(i = 0; i < s.getInventorySize(); i++) {
        cur = s.getProduct(i);
        System.out.println(cur);
        for(int j = i + 1; j < s.getInventorySize(); j++) {
            if(cur.equals(s.getProduct(j)))
                System.out.println(cur.getName() + " is the same price as " + s.getProduct(j).getName());
        }
    }
    

内容的提问来源于stack exchange,提问作者Ali Fuat Akyemiş

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:35:03