hashCode two objects () are the same, equals () certainly is true, right?

In java, equals and hashcode design requirements are equal equals, the hashcode necessarily be equal, but not vice versa.

Why is there such a demand?

In the collection, such as HashSet, the requirements placed objects can not be repeated, how it is determined?

First calls hashcode, if hashcode equal, continue to call equals, also equal, is considered to be repeated.

If rewrite equals, if they do not override hashcode, the hashcode is inherited from Object Returns memory encoding, which may occur when equals are equal, unequal and hashcode, when you use a collection of objects, it will not wait for the right result

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 ;
     }

Guess you like

Origin www.cnblogs.com/sttcorcy/p/11652598.html