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

如何避免向ArrayList中添加productName重复的Product对象?

解决ArrayList中避免重复添加同productName的Product对象问题

方案一:重写Product类的equals()和hashCode()方法

ArrayList的contains()方法底层依赖对象的equals()方法,默认逻辑是比较对象内存地址,所以需要重写这两个方法,让判断逻辑基于productName字段:

public class Product {
    private String productName;
    private int costPrice;
    private int sellingPrice;

    // 构造方法、getter/setter方法自行补充

    @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(productName, product.productName);
    }

    @Override
    public int hashCode() {
        return Objects.hash(productName);
    }
}

重写后,原来的contains()判断逻辑就能正常生效——只要两个Product的productName相同,equals()就会返回true,contains()就能识别出重复。

方案二:手动遍历ArrayList检查productName

如果无法修改Product类的代码,可以直接遍历列表,逐个对比目标字段:

boolean isDuplicate = false;
String newProductName = product.getProductName();
for (Product p : arraylist) {
    if (newProductName.equals(p.getProductName())) {
        isDuplicate = true;
        break;
    }
}

if (isDuplicate) {
    Toast.makeText(getContext(), "Product already exists", Toast.LENGTH_SHORT).show();
} else {
    arraylist.add(product);
    adapter.notifyDataSetChanged();
}

这种方式不需要改动原有POJO类,直接通过遍历对比字段实现重复校验。

额外优化建议

如果需要频繁执行重复检查操作,推荐使用HashSet(配合重写的equals和hashCode),它的contains()方法时间复杂度为O(1),比ArrayList的O(n)效率更高;如果需要保持元素添加顺序,可以改用LinkedHashSet。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 12:57:09