繼承關(guān)系中子類使用@Data注解問題

HashSet中使用@Data注解問題

平時習慣使用lombok工具,免去了我們寫get、set方法之類的,當然了,我們使用@Data注解后,equals()、hashCode()toString() 也省卻了。但是當你代碼存在繼承關(guān)系時,就得留心結(jié)果是否是你想要的了?

下面我直接列舉個例子吧:

父類:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Tag {

  private Long id;

  private String tagName;

  private String position;
}

子類:

@Data
@NoArgsConstructor
public class UserTag extends Tag {

  private Long userId;

  public UserTag(Long id, String tagName, String position, Long userId) {
    super(id, tagName, position);
    this.userId = userId;
  }
}

其實關(guān)系就這么easy,最后我們test來說明問題

public class UserTagTest {

  public static void main(String[] args) {
    UserTag firstUserTag = new UserTag(1L, "tag1", "up", 2000L);
    UserTag secondUserTag = new UserTag(2L, "tag2", "down", 2000L);

    Set<Tag> tagSet = new HashSet<>();
    boolean firstAdd = tagSet.add(firstUserTag);
    boolean secondAdd = tagSet.add(secondUserTag);

    System.out.println("firstAdd:" + firstAdd);
    System.out.println("secondAdd:" + secondAdd);
    System.out.println("tagSet size:" + tagSet.size());
  }
}

運行實際結(jié)果:

firstAdd:true
secondAdd:false
tagSet size:1

當看著實際結(jié)果和預(yù)期結(jié)果不同,當然了,很容易就想到是equals()hashCode()的問題。最后我反編譯看著@Data幫我們生成的equals()hashCode(),如下:

public boolean equals(Object o) {
    if (o == this) {
      return true;
    } else if (!(o instanceof UserTag)) {
      return false;
    } else {
      UserTag other = (UserTag)o;
      if (!other.canEqual(this)) {
        return false;
      } else {
        Object this$userId = this.getUserId();
        Object other$userId = other.getUserId();
        if (this$userId == null) {
          if (other$userId != null) {
            return false;
          }
        } else if (!this$userId.equals(other$userId)) {
          return false;
        }

        return true;
      }
    }
  }

  protected boolean canEqual(Object other) {
    return other instanceof UserTag;
  }

  public int hashCode() {
    int PRIME = true;
    int result = 1;
    Object $userId = this.getUserId();
    int result = result * 59 + ($userId == null ? 43 : $userId.hashCode());
    return result;
  }

實際上只比較了userId,說到這,得到上面的運行結(jié)果也就很正常了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容