重写equals和hashcode时用到的属性必须一致么???

askquestion_003 askquestion_003 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

class People {
private String name;
private int age;

public People(int age, String name) {
super();
this.age = age;
this.name = name;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
People other = (People) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
}

问题:
1.equals和hashcode只要重写其中一个,从业务上是否要求一定要重写另一个?否则何种情况会有弊端
2.如果同时重写两者,是否两者用到的属性必须一致,而不能一个多某个属性,一个少?
3.何种情况可以单独用其中一个,而没有副作用?
...全文

相关推荐

【面试】hashCode与equals两者之间的关系 / == 和equals / 为什么要重写equals方法 / 重写equals /hashcode方法 / 为什么要重写hashCode方法

文章目录1、hashCode与equals两者之间的关系2、== 和equals的区别`3、为什么要重写equals()方法?4、重写equals()方法5、为什么要重写hashCode()方法?6、什么时候需要重写hashCode()方法?7、重写hashCode()方法: 1、hashCode与equals两者之间的关系 如果两个对象相同(即用equals比较返回true),那么它们的hashCode值一定要相同!!!! 如果两个对象不同(即用equals比较返回false),那么它们的hashCode值可能相同也可能不同。 如果两个对象的hashCode相同(存在哈希冲突),那么它们可

weixin_38693720

java中为何重写equals时必须重写hashCode方法详解

主要给大家介绍了关于java中为什么重写equals时必须重写hashCode方法的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

weixin_38700430

java中重写equals()方法的同时要重写hashcode()方法(详解)

下面小编就为大家带来一篇java中重写equals()方法的同时要重写hashcode()方法(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

weixin_38711008

关于重写equals,hashcode以及compareTo方法!

关于重写equals,hashcode以及compareTo方法!

aa0123

重写hashCode()和equals()方法详细介绍

主要介绍了重写hashCode()和equals()方法详细介绍,涉及重写equals()方法,重写hashCode()方法,重写equals()而不重写hashCode()的风险等相关内容的介绍,具有一定借鉴价值,需要的朋友可以参考下

weixin_38674763
评论 8
收藏 已收藏
分享
返回顶部
askquestion_003
Java SE 62,621 成员 307,251 内容