1, ==是比较句柄,若ob1==ob2,也就是两个句柄指向一个对象。所以ob1.hashcode()==ob2.hashcode()和ob1.equals(ob2) == true;

2,hashcode相同的两个对象,ob1.equals(ob2)不一定为true;ob1.equals(ob2)为true的两个对象,hashcode应该相同。即覆写equals方法时应同时覆写hashcode方法

3,hashcode一般用到HashSet,HashMap中,根据hashcode来确定存储位置,如果hashcode相同,再用equals来判断Set中的唯一性。

HashMap中put方法的源代码是:

  1. public V put(K key, V value) { 

  2.         if (key == null

  3.             return putForNullKey(value); 

  4.         int hash = hash(key.hashCode()); 

  5.         int i = indexFor(hash, table.length); 

  6.         for (Entry<K,V> e = table[i]; e != null; e = e.next) { 

  7.             Object k; 

  8.             if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { 

  9.                 V oldValue = e.value; 

  10.                 e.value = value; 

  11.                 e.recordAccess(this); 

  12.                 return oldValue; 

  13.             } 

  14.         } 

  15.  

  16.         modCount++; 

  17.         addEntry(hash, key, value, i); 

  18.         return null

  19.     } 




看e.hash == hash && ((k = e.key) == key || key.equals(k))这句,即先判定hashcode是否相同,再判断equals是否为true