加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 维护特定条件的hashCode契约,equals()取决于两个整数

发布时间:2020-12-15 04:45:51 所属栏目:Java 来源:网络整理
导读:我有一个基本的结构类: class Employee {int eId;String eName;Employee(int id,String name) { this.eId= id; this.eName= name;} 如果满足以下任何条件,则equals()应返回true: eId是一样的. eName是相同的. eName的长度相同. 我在覆盖equals()时没有问题
我有一个基本的结构类:

class Employee {
int eId;
String eName;

Employee(int id,String name) {
    this.eId= id;
    this.eName= name;
}

如果满足以下任何条件,则equals()应返回true:

> eId是一样的.
> eName是相同的.
> eName的长度相同.

我在覆盖equals()时没有问题,但是,为了维护哈希代码契约,我也应该覆盖hashCode().因此,hashCode应该依赖于eId和eName.length()(如果eNames相等,它们的长度也将相等).所以有四种情况:

Employee e1 = new Employee(4,"John");
Employee e2 = new Employee(3,"Jane");
Employee e3 = new Employee(4,"Jim");
Employee e4 = new Employee(7,"Random");

hashCode()应返回e1,e2和e3的相同值以及e4的不同值.我无法想出满足这一要求的逻辑.

这是确切的问题:

Create a class (having parameters name,id etc). Show that if 2 objects of this class will be compared then they should return true in any of below case :

A. Id of both are same.

B. Name of both are same.

C. Length of name’s of both are same.

Make sure HashCode contract should not violate.

解决方法

你遇到了麻烦,因为你的平等概念是不一致的.具体来说,它不是传递性的,.equals()的合同要求.

It is transitive: for any non-null reference values x,y,and z,if x.equals(y) returns true and y.equals(z) returns true,then x.equals(z) should return true.

根据您的定义,e1等于e2和e3,但e2不等于e3.这与Java的平等概念不相容.这也是您在定义合理的.hashCode()实现时遇到麻烦的原因.

但是,您可以做的是定义自定义Comparator(或Ordering,如果您使用的是Guava).对于大多数用例(如排序,搜索或过滤),您应该能够像使用.equals()方法一样使用单独的Comparator实例.您正在有效地尝试定义等效对象,而不是相等对象.

如果由于某种原因无法使用单独的Comparator,那么您的Employee对象将基本上不一致,即使您应该实现“可行”的.hashCode(),也会出现问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读