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

泛型单向链表toString异常:list.contains始终返回false求助

问题分析与解决方案

我来帮你定位问题啦!你遇到的contains()始终返回false、去重失效的核心原因,是Cycle类的equals方法没有正确重写Object类的equals方法。

为什么会这样?

Java中,重写equals方法必须严格遵循Object类的方法签名:public boolean equals(Object obj)。你现在写的:

public boolean equals(Cycle cycle) {
    return this.getPrice() == cycle.getPrice();
}

这不是重写,而是重载了一个新的equals方法。而ArrayList.contains()底层调用的是Object.equals()(默认比较对象引用地址),不会用到你自定义的这个重载方法。所以即使两个Cycle对象的price相同,因为是不同的对象实例,contains()会判定它们不相等,导致去重逻辑失效。

修复方案

修改Cycle类的equals方法,按照正确的重写规则来实现,同时建议同步重写hashCode方法(Java规范要求:如果两个对象equals返回true,它们的hashCode必须相等):

public class Cycle{
    private int price;
    Cycle(int price) {
        this.price = price;
    }
    int getPrice() {
        return this.price;
    }
    @Override
    public String toString() {
        return "" + this.price;
    }

    // 正确重写Object的equals方法
    @Override
    public boolean equals(Object obj) {
        // 先判断是否是同一个引用
        if (this == obj) return true;
        // 判断是否为null或者类型不匹配
        if (obj == null || getClass() != obj.getClass()) return false;
        // 强转后比较price
        Cycle cycle = (Cycle) obj;
        return price == cycle.price;
    }

    // 同步重写hashCode
    @Override
    public int hashCode() {
        return Integer.hashCode(price);
    }
}

验证效果

修改后,当你调用list.contains(walk.getElement())时,ArrayList会使用你重写后的equals方法比较Cycle对象的price值,只要price相同就会返回true,toString方法里的去重逻辑就能正常工作了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:30:28