java 怎么使用自带的equals方法,Java如何使用EqualsBuilder类实现equals()方法?

package org.nhooo.example.commons.lang;

public class ObjectEqualsDemo {

public static void main(String[] args) {

Book book1 = new Book(1L, "Spring Boot in Action", "Craig Walls");

Book book2 = new Book(2L, "Docker in Action", "Jeff Nickoloff");

Book book3 = book1;

System.out.println("book1.equals(book2) = " + book1.equals(book2));

System.out.println("book3.equals(book1) = " + book3.equals(book1));

}

}package org.nhooo.example.commons.lang;

import org.apache.commons.lang3.builder.EqualsBuilder;

import org.apache.commons.lang3.builder.HashCodeBuilder;

import java.io.Serializable;

public class Book implements Serializable {

private Long id;

private String title;

private String author;

public Book(Long id, String title, String author) {

this.id = id;

this.title = title;

this.author = author;

}

//〜在这里实现获取器和设置器。

public boolean equals(Object o) {

if (o == this) {

return true;

}

if (!(o instanceof Book)) {

return false;

}

Book that = (Book) o;

return new EqualsBuilder()

.append(this.id, that.id)

.append(this.title, that.title)

.append(this.author, that.author)

.isEquals();

// 您还可以使用EqualsBuilder类的反射。

// 返回EqualsBuilder.reflectionEquals(this,that);

}

public int hashCode() {

return new HashCodeBuilder()

.append(id)

.append(title)

.append(author)

.toHashCode();

// 甚至使用最简单的反射方法

// 下面。

// 返回HashCodeBuilder.reflectionHashCode(this);

}

}

Maven依赖

org.apache.commons

commons-lang3

3.9

commons-lang3.svg?label=Maven%20Central

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值