为什么实现了equals()就必须实现hashCode()?

时间:2022-05-07
本文章向大家介绍为什么实现了equals()就必须实现hashCode()?,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

我们先来看下面这个简单的例子,然后运行她:

class Person{ private String name; private int age; public Person(String name,int age) { this.name = name; this.age = age; } public void setAge(int age){ this.age = age; } @Override public boolean equals(Object obj) { return this.name.equals(((Person)obj).name) && this.age== ((Person)obj).age; } } public class Main { public static void main(String[] args) { Person p1 = new Person("Hezhuofan", 29); System.out.println(p1.hashCode()); HashMap<Person, Integer> hashMap = new HashMap<Person, Integer>(); hashMap.put(p1, 1); System.out.println(hashMap.get(new Person("Hezhuofan", 29))); } }

运行结果:

911511966 null

在这里我们只override了equals方法,也就是说如果两个Person对象,如果他们的姓名和年龄相等,则认为是同一个人。

  这段代码本来的意愿是希望输出“1”,但最后输出的是“null”。为什么呢?原因就在于override equals方法的同时没有 override hashCode方法。

  虽然通过重写equals方法使得逻辑上姓名和年龄相同的两个对象被判定为相等的对象(跟String类类似),但是要知道默认情况下,hashCode方法是将对象的存储地址进行映射。那么上述代码的输出结果为“null”就不足为奇了。原因很简单,p1指向的对象和

  System.out.println(hashMap.get(new Person("Hezhuofan", 29)));这句中的new Person("Hezhuofan", 29)生成的是两个对象,它们的存储地址肯定不同。下面是HashMap的get方法的具体实现:

public V get(Object key) { if (key == null) return getForNullKey(); int hash = hash(key.hashCode()); for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) return e.value; } return null; }

所以在hashmap进行get操作时,因为得到的hashcdoe值不同(注意,上述代码也许在某些情况下会得到相同的hashcode值,不过这种概率比较小,因为虽然两个对象的存储地址不同也有可能得到相同的hashcode值),所以导致在get方法中for循环不会执行,直接返回null。

  因此如果想上述代码输出结果为“1”,很简单,只需要重写hashCode方法,让equals方法和hashCode方法始终在逻辑上保持一致性。

@Override public int hashCode() { return name.hashCode()*37+age; }

这样一来的话,输出结果就为“1”了。

“设计hashCode()时最重要的原则就是:无论什么时候,对同一个对象调用hashCode()都应该产生同样的值。如果在将一个对象用put()添加进HashMap时产生一个hashCode值,而用get()取出时却产生了另一个hashCode值,那么就无法获取该对象了。所以如果你的hashCode方法依赖于对象中易变的数据,你就要小心了,因为此数据发生变化时,hashCode()方法就会生成一个不同的散列码”。

总之,设计hashCode一定要依赖于不易变的数据!

有关本文的源码君可以移步“阅读原文”git或在线阅读:

https://github.com/importsource/util/tree/master/src/main/java/com/importsource/util/hash