重写equals和hashCode引发的思考

关于重写equals方法

最近小伙伴问了我个问题:
在Set里存放对象,如果有两个对象属性相同,那么怎么能保证只存在一个对象?
HashSet是基于HashMap实现的,所以要看看HashMap的源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
           //判断该hashCode的key是否存在
       if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
           //如果该hashCode存在,调用equals比较key的值
           if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

可以看到,HashMap是根据hashCode来确定在Node数组中的位置,那么要使HashSet能够对对象去重,就首先需要重写对象的Hash方法,使相同值的对象的HashCode相等,其次还需要重写equals方法,因为即使hashCode相同还是会存放到Map中,这种情况属于Hash冲突,会使用链表存放该对象。

HashCode和equals的关系?

  • 以下是我的理解

    equals比较变量或者对象是否“相同”,这个相同是偏向于业务上的相同,和人理解的“相同”是一个概念。计算机判断的“相同”是hashCode是一致,但如果一个对象,那么计算机并不知道怎么判断他们是否相同(总不能比较对象字节流吧。。),那么就只能使用Object的hashCode方法判断值是否一致。如果没重写就会导致计算机认为是不同的对象。所以就有了重写equals()一定要重写hashcode()的说法了。但注意hashCode相同equals不一定要相同,因为这个是由于hash算法的优劣决定的。

1
2
3
4
5
6
7
//下面是Object的生成hashCode方法,根据内存地址生成
/** This is stated explicitly here because it is important for
implementations to understand that equals() and hashCode() must
absolutely, positively work properly -- i.e., two Address
objects representing the same address are both equal (via
equals()) and have the same hash code. */
public int hashCode();

注意Integer等包装类型:

1.Integer 类型的值在[-128,127] 期间,Integer 用 “==”是可以的 , Integer 与 int 类型比较(==)比较的是值。Integer和int比较会自动拆箱,可以用==或equals

2.大于127比较两个Integer用intValue 然后在 == 或者直接equals