两个对象的 hashCode()相同,则 equals()也一定为 true,对吗?

在java中,equals和hashcode是有设计要求的,equals相等,则hashcode一定相等,反之则不然。

为何会有这样的要求?

在集合中,比如HashSet中,要求放入的对象不能重复,怎么判定呢?

首先会调用hashcode,如果hashcode相等,则继续调用equals,也相等,则认为重复。

如果重写equals后,如果不重写hashcode,则hashcode就是继承自Object的,返回内存编码,这时候可能出现equals相等,而hashcode不等,你的对象使用集合时,就会等不到正确的结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
 
        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

posted on 2019-10-11 10:31  sttcor  阅读(5285)  评论(0)    收藏  举报