为什么我们需要重写hashCode和equals? [英] Why we need to override hashCode and equals?

查看:210
本文介绍了为什么我们需要重写hashCode和equals?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认使用hashCode和equals可以正常工作. 我已经将对象与哈希表(如HashMap)一起使用,而没有重写此方法,这很好.例如:

By default hashCode and equals works fine. I have used objects with hash tables like HashMap, without overriding this methods, and it was fine. For example:

public class Main{
public static void main(String[] args) throws Exception{
    Map map = new HashMap<>();
    Object key = new Main();
    map.put(key, "2");
    Object key2 = new Main();
    map.put(key2, "3");
    System.out.println(map.get(key));
    System.out.println(map.get(key2));
}
}

此代码可以正常工作.默认情况下,hashCode返回对象的内存地址,并且equals检查两个对象是否相同.那么使用此方法的默认实现有什么问题?

This code works fine. By default hashCode returning memory address of object, and equals checks if two objects is the same. So what is the problem with using default implementation of this methods?

推荐答案

请注意,我有一个旧的pdf示例,

Note this example from an old pdf I have:

此代码

    public class Name {

private String first, last;

public Name(String first, String last) { this.first = first; this.last = last;

}

public boolean equals(Object o) {

if (!(o instanceof Name)) return false;

Name n = (Name)o;

return n.first.equals(first) && n.last.equals(last);

}

public static void main(String[] args) {

Set s = new HashSet();

s.add(new Name("Donald", "Duck"));

System.out.println(

s.contains(new Name("Donald", "Duck")));

}

}

...将不会总是得到相同的结果,因为pdf中有说明

...will not always give the same result because as it is stated in the pdf

唐纳德(Donald)在集合中,但集合中找不到他.名称类 违反了hashCode合同

Donald is in the set, but the set can’t find him. The Name class violates the hashCode contract

因为在这种情况下,有两个字符串组成对象,所以哈希码也应该由这两个元素组成.

Because, in this case, there are two strings composing the object the hashcode should also be composed of those two elements.

要修复此代码,我们应该添加一个hashCode方法:

To fix this code we should add a hashCode method:

public int hashCode() { 
return 31 * first.hashCode() + last.hashCode();
}

pdf中的这个问题结尾表示我们应该

This question in the pdf ends saying that we should

在覆盖等于时覆盖hashCode

override hashCode when overriding equals

这篇关于为什么我们需要重写hashCode和equals?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆