JAVA重新对象equals方法_JAVA对象重写equals方法与hashcode方法

需要比较两个对象是否相等,需要重写equals方法,重写equals方法必重写hashcode方法.

参考资料:

下面是自己写public class Cat {

private String name;

private String color;

private String weight;

private String high;

private int year;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getColor() {

return color;

}

public void setColor(String color) {

this.color = color;

}

public String getWeight() {

return weight;

}

public void setWeight(String weight) {

this.weight = weight;

}

public String getHigh() {

return high;

}

public void setHigh(String high) {

this.high = high;

}

public int getYear() {

return year;

}

public void setYear(int year) {

this.year = year;

}

/* (non-Javadoc)

* @see java.lang.Object#equals(java.lang.Object)

*/

@Override

public boolean equals(Object obj) {

// TODO Auto-generated method stub

if(this == obj) {

return true;

}

if(null == obj) {

return false;

}

if(this.getClass() != obj.getClass()) {

return false;

}

Cat cat = (Cat)obj;

if (

this.name.equals(cat.getName()) &&

this.color.equals(cat.getColor()) &&

this.weight.equals(cat.getWeight()) &&

this.high.equals(cat.getHigh()) &&

this.year == cat.getYear()

) {

return true;

}

return super.equals(obj);

}

/* (non-Javadoc)

* @see java.lang.Object#hashCode()

*/

@Override

public int hashCode() {

// TODO Auto-generated method stub

return Objects.hash(this.name,this.color,this.weight,this.high,this.year);

}

}

equals方法需要与hashcode方法一致.

比如说,我们忽略cat的属性year,即无论year是否相同,只要其它的属性相同,那么两个对象就相同,此时的equals方法就需要删除this.year == cat.getYear()的判断,hashcode方法里也需要将year参数删去.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值