Overriding equals() & hashCode() in sub classes … considering super fields

前端 未结 10 1254
一个人的身影
一个人的身影 2020-12-07 13:19

Is there a specific rule on how Overriding equals() & hashCode() in sub classes considering super fields ?? k

10条回答
  •  独厮守ぢ
    2020-12-07 14:00

    It's worth noting that the IDE auto generation maybe has taken into consideration super class,just provided that the equals() and hashCode() of super class exists yet. That is, should auto generate these two functions of super first, and then auto generate of the child. I got below right example under Intellj Idea:

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;
    
        TActivityWrapper that = (TActivityWrapper) o;
    
        return data != null ? data.equals(that.data) : that.data == null;
    }
    
    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (data != null ? data.hashCode() : 0);
        return result;
    }
    

    The problem happens just when you don't auto generate super's in first. Please check above under Netbeans.

提交回复
热议问题