商城首页欢迎来到中国正版软件门户

您的位置:首页 >ArrayList 第一个元素为 null 的原因及解决方法

ArrayList 第一个元素为 null 的原因及解决方法

  发布于2026-04-19 阅读(0)

扫一扫,手机访问

Java ArrayList 第一个元素总是 null 的原因与修复方法

当使用 ArrayList 存储对象时,若 getProduct(int index) 方法中错误地将索引边界判断写为 index > 0,会导致索引 0 被拒绝访问而返回 null,这是典型的零索引误判问题。

当使用 ArrayList 存储对象时,若 `getProduct(int index)` 方法中错误地将索引边界判断写为 `index > 0`,会导致索引 0 被拒绝访问而返回 null,这是典型的零索引误判问题。

在 Java 中,ArrayList(以及所有基于数组的集合)采用 0-based indexing(从 0 开始编号),即第一个元素位于索引 0,第二个在 1,依此类推。然而,在提供的 Store 类中,getProduct 方法存在一个关键逻辑缺陷:

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

该条件 index > 0 直接排除了合法且最常用的索引 0 —— 即使 products 非空、products.get(0) 完全有效,此方法仍会返回 null。这正是用户观察到“第一个产品总是 null,但第二、第三个正常”的根本原因。

✅ 正确的边界检查应为:

public Product getProduct(int index) {
    if (index >= 0 && index < products.size()) {
        return products.get(index);
    }
    return null; // 或更佳做法:抛出 IndexOutOfBoundsException
}

? 提示:Java 集合类(如 ArrayList.get())本身已内置越界检查,直接委托调用更安全、更符合惯例:

public Product getProduct(int index) {
    return products.get(index); // 自动抛出 IndexOutOfBoundsException(推荐)
}

若需静默容错,再封装 try-catch;但教学与生产环境中,显式暴露错误比静默返回 null 更利于调试和健壮性。

⚠️ 其他注意事项

  • getProductIndex(Product) 依赖 ArrayList.indexOf(),其正确性基于 Product.equals(Object) 的实现。当前 Product.equals(Product) 是自定义方法,但未重写 Object.equals(Object)(参数类型为 Object),导致 indexOf() 实际调用的是默认引用比较,可能无法按预期匹配。建议补充标准重写:

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Product product = (Product) obj;
        return Double.compare(product.price, price) == 0 &&
               Objects.equals(id, product.id) &&
               Objects.equals(name, product.name);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(id, name, price);
    }
  • 初始化 ArrayList 时无需指定容量(除非预知规模),但确保其非 null:ArrayList<Product> products = new ArrayList<>(); 已足够安全。

总结:零索引是 Java 的基础约定,任何索引校验都必须包含 >= 0。一次 > 与 >= 的笔误,就足以引发难以追踪的 null 异常。养成审查边界条件的习惯,并优先复用 JDK 原生行为,是写出可靠集合操作代码的关键。

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注