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

如何检测两个StateMachine实例的状态差异?equals方法判断异常

解决StateMachine实例equals判定不一致的问题

问题根源

Java所有类默认继承Object类,Object.equals()的默认逻辑是比较对象的内存地址,而非对象的内容。你的LED和StateMachine都没重写equals()和hashCode()方法,所以哪怕两个实例状态完全一致,instance1.equals(instance2)也会因为是不同对象实例而返回false。

解决步骤

要实现基于内容的相等性判断,必须为LED和StateMachine分别重写equals()和hashCode(),且要遵守约定:若a.equals(b)为true,则a.hashCode()必须等于b.hashCode(),因此两个方法要同时重写。

1. 重写LED类的equals与hashCode

import java.util.Objects;

public class LED {
    public boolean onState;
    public boolean updateRequired;
    public int Id;
    public String Key;
    public Drawable onStateDrawable;
    public Drawable offStateDrawable;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        LED led = (LED) o;
        return onState == led.onState &&
                updateRequired == led.updateRequired &&
                Id == led.Id &&
                Objects.equals(Key, led.Key) &&
                Objects.equals(onStateDrawable, led.onStateDrawable) &&
                Objects.equals(offStateDrawable, led.offStateDrawable);
    }

    @Override
    public int hashCode() {
        return Objects.hash(onState, updateRequired, Id, Key, onStateDrawable, offStateDrawable);
    }
}

2. 重写StateMachine类的equals与hashCode

HashMap的equals()会自动比较键值对内容(前提是键和值的类已正确重写equals()),因此直接用Objects.equals()比较map即可:

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class StateMachine{    
    private Map<Integer, LED> lamps = new HashMap<>();

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        StateMachine that = (StateMachine) o;
        return Objects.equals(lamps, that.lamps);
    }

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

    // 如需外部访问lamps,可添加getter
    public Map<Integer, LED> getLamps() {
        return lamps;
    }
}

注意事项

  • 若Drawable是自定义类且未重写equals(),需要同步为其实现该方法与hashCode(),否则Drawable字段仍会按内存地址比较。
  • 后续若给类新增字段,要同步更新equals()和hashCode(),否则会导致相等性判断不准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 18:04:56