---
title: "在重写了对象的equals方法后，还需要重写hashCode方法吗?"
author: "cantellow"
date: "2009-08-19T21:08:34Z"
tags: []
slug: "equals-hashcode"
draft: false
lastmod: "2009-08-19T21:08:34Z"
id: 453145
url: "https://cantellow.iteye.com/blog/453145"
---

首先说建议的情况：  比如你的对象想放到Set集合或者是想作为Map的key时（非散列的Set和Map，例如TreeSet,TreeMap等），那么你必须重写equals()方法，这样才能保证唯一性。当然，在这种情况下，你不想重写hashCode()方法，也没有错。但是，对于良好的编程风格而言，你应该在重写equals（）方法的同时，也重写hashCode()方法。 

然后再说说必须重写hashCode()的情况：   
    如果你的对象想放进散列存储的集合中（比如：HashSet,LinkedHashSet）或者想作为散列Map（例如：HashMap,LinkedHashMap等等）的Key时，在重写equals()方法的同时，必须重写hashCode()方法。 

这里我想讲讲sun的设计者为什么需要设计hashcode方法，也许这样你就应该知道什么时候该重写它了。   
数据结构有一种为了提高查找的效率而存在的数据结构——散列表，散列表其实是普通数组概念的推广，因为可以对数组进行直接寻址，故可以再O（1）时间内访问数组的任意元素，thinking in java中有个对hashmap简单的实现，我们来看看你就明白了： 

 

01. //: containers/SimpleHashMap.java
02. // A demonstration hashed Map.
03. import java.util.\*;
04. import net.mindview.util.\*;
05. public class SimpleHashMap&lt;K,V&gt; extends AbstractMap&lt;K,V&gt; {
06. // Choose a prime number for the hash table
07. // size, to achieve a uniform distribution:
08. static final int SIZE = 997;
09. // You can't have a physical array of generics,
10. // but you can upcast to one:
11. @SuppressWarnings("unchecked")
12. LinkedList&lt;MapEntry&lt;K,V&gt;&gt;\[] buckets =
13. new LinkedList\[SIZE];//List数组里每项是个List，数组下标是hashcode方法的返回值再经过散列函数得到的，相当于散列表的关键字，它亦代表着每个对象的关键字。（不能显示new一个泛型数组，但是你可以new一个泛型数组的引用，如有需要以后可以将普通数组转型为泛型数组）。
14. public V put(K key, V value) {//将这个对键值放进hashmap中。
15. V oldValue = null;
16. int index = Math.abs(key.hashCode()) % SIZE;//这里就是通过散列函数对hashcode的返回值处理得到一个关键字，它代表了对象在数组里的位置，既是数组下标。
17. if(buckets\[index] == null)
18. buckets\[index] = new LinkedList&lt;MapEntry&lt;K,V&gt;&gt;();//如果是第一次散列到这个数组下标，那么就新生成一个LinkedList，可以看到它里面保存的是MapEntry&lt;K,V&gt;键和值。
19. LinkedList&lt;MapEntry&lt;K,V&gt;&gt; bucket = buckets\[index];//将这个LinkedList赋值给一个bucket（桶），以后就直接在这个bucket进行操作。
20. MapEntry&lt;K,V&gt; pair = new MapEntry&lt;K,V&gt;(key, value);
21. boolean found = false;
22. ListIterator&lt;MapEntry&lt;K,V&gt;&gt; it = bucket.listIterator();
23. while(it.hasNext()) {
24. MapEntry&lt;K,V&gt; iPair = it.next();
25. if(iPair.getKey().equals(key)) {//如果已经存在同一个键值，那么就更新value。
26. oldValue = iPair.getValue();
27. it.set(pair); // Replace old with new
28. found = true;
29. break;
30. }
31. }
32. if(!found)
33. buckets\[index].add(pair);//如果是一个新的键值，那么直接添加到这个LinkedList中。
34. return oldValue;
35. }
36. public V get(Object key) {//看hashmap是如何凭借hashcode方法快速定位到键值。
37. int index = Math.abs(key.hashCode()) % SIZE;\[color=red]//与put方法中的作用一样，生成数组下标，因为我存的时候就是存到这个地方的，那么我取的时候直接访问buckets\[index]。\[/color]
38. if(buckets\[index] == null) return null;//直接访问这个数组下标的LinkedList，如果为null，则返回。
39. for(MapEntry&lt;K,V&gt; iPair : buckets\[index])//为什么要用LinkedList，因为hashcode方法产生的散列码不能完全确定一个对象，也就是说会和其他对象发生“碰撞”，即散列到同一个数组下标，解决这个问题的组号办法就是定义一个List把它们保存起来，但是在这个List中，我们必须保证能用equals方法确定对象的身份，这也就是为什么很多人说hashcode()相等，equals()不一定相等，而equals()相等的两个对象，hashcode()一定相等。所以这里要直接在LinkedList执行线性查找。
40. if(iPair.getKey().equals(key))
41. return iPair.getValue();
42. return null;
43. }
44. public Set&lt;Map.Entry&lt;K,V&gt;&gt; entrySet() {
45. Set&lt;Map.Entry&lt;K,V&gt;&gt; set= new HashSet&lt;Map.Entry&lt;K,V&gt;&gt;();
46. for(LinkedList&lt;MapEntry&lt;K,V&gt;&gt; bucket : buckets) {
47. if(bucket == null) continue;
48. for(MapEntry&lt;K,V&gt; mpair : bucket)
49. set.add(mpair);
50. }
51. return set;
52. }
53. public static void main(String\[] args) {
54. SimpleHashMap&lt;String,String&gt; m =
55. new SimpleHashMap&lt;String,String&gt;();
56. m.putAll(Countries.capitals(25));
57. System.out.println(m);
58. System.out.println(m.get("ERITREA"));
59. System.out.println(m.entrySet());
60. }
61. } /* Output:
62. {CAMEROON=Yaounde, CONGO=Brazzaville, CHAD=N'djamena, COTE D'IVOIR (IVORY COAST)=Yamoussoukro, CENTRAL AFRICAN REPUBLIC=Bangui, GUINEA=Conakry, BOTSWANA=Gaberone, BISSAU=Bissau, EGYPT=Cairo, ANGOLA=Luanda, BURKINA FASO=Ouagadougou, ERITREA=Asmara, THE GAMBIA=Banjul, KENYA=Nairobi, GABON=Libreville, CAPE VERDE=Praia, ALGERIA=Algiers, COMOROS=Moroni, EQUATORIAL GUINEA=Malabo, BURUNDI=Bujumbura, BENIN=Porto-Novo, BULGARIA=Sofia, GHANA=Accra, DJIBOUTI=Dijibouti, ETHIOPIA=Addis Ababa}
63. Asmara
64. \[CAMEROON=Yaounde, CONGO=Brazzaville, CHAD=N'djamena, COTE D'IVOIR (IVORY COAST)=Yamoussoukro, CENTRAL AFRICAN REPUBLIC=Bangui, GUINEA=Conakry, BOTSWANA=Gaberone, BISSAU=Bissau, EGYPT=Cairo, ANGOLA=Luanda, BURKINA FASO=Ouagadougou, ERITREA=Asmara, THE GAMBIA=Banjul, KENYA=Nairobi, GABON=Libreville, CAPE VERDE=Praia, ALGERIA=Algiers, COMOROS=Moroni, EQUATORIAL GUINEA=Malabo, BURUNDI=Bujumbura, BENIN=Porto-Novo, BULGARIA=Sofia, GHANA=Accra, DJIBOUTI=Dijibouti, ETHIOPIA=Addis Ababa]

怎样？现在应该知道hashcode方法的作用了吧，它就是用来提高效率的，有句话说得好：为速度而散列。因为散列的Set和Map是基于hashcode方法来查找对象的，所以你在使用这些类的时候一定要覆盖hashcode方法，而非散列的Set和Map，例如TreeSet,TreeMap等，它们只需equals方法就可以唯一确定对象的身份。这样说，想必已经很清楚了吧。