在實際使用中如果遇到對象作爲HashMap結構的key,則一定要注意重寫equals和hashCode兩個方法。以JDK8爲例,HashMap在put(K key, V value)方法和containsKey(Object key)方法都會進行當前HashMap中是否已有待放入的key,比如containsKey(Object key)方法:
/**
* Returns <tt>true</tt> if this map contains a mapping for the
* specified key.
*
* @param key The key whose presence in this map is to be tested
* @return <tt>true</tt> if this map contains a mapping for the specified
* key.
*/
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
/**
* Computes key.hashCode() and spreads (XORs) higher bits of hash
* to lower. Because the table uses power-of-two masking, sets of
* hashes that vary only in bits above the current mask will
* always collide. (Among known examples are sets of Float keys
* holding consecutive whole numbers in small tables.) So we
* apply a transform that spreads the impact of higher bits
* downward. There is a tradeoff between speed, utility, and
* quality of bit-spreading. Because many common sets of hashes
* are already reasonably distributed (so don't benefit from
* spreading), and because we use trees to handle large sets of
* collisions in bins, we just XOR some shifted bits in the
* cheapest possible way to reduce systematic lossage, as well as
* to incorporate impact of the highest bits that would otherwise
* never be used in index calculations because of table bounds.
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
可以看到,在判斷當前Map中是否有要查詢的Object key時,先進入混淆函數hash(Object key)計算得出對應的hash值,再根據hash值和equals()函數結果判斷是否有當前key。所以,尤其在自定義對象作爲key的時候,一定要覆蓋equals和hashCode兩個方法,equals方法容易實現,hashCode方法就需要開發人員合理地設計了,因爲要遵循兩個對象equals爲true,那麼這兩個對象中的每個對象調用 hashCode
方法都必須生成相同的整數結果。
測試代碼:
給學生髮學生卡,每個學生對應一個唯一的學號
/**
* @author lingyingqiaoren
* @since 2019-08-02
*/
public class Student {
/**
* 學號
*/
private Integer id;
/**
* 姓名
*/
private String name;
public Student() {
}
public Student(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return this.id;
}
@Override
public String toString(){
return "Student{id:" + this.id + ";name:" + this.name + "}";
}
@Override
public boolean equals(Object o){
return this.id.equals(((Student) o).getId());
}
@Override
public int hashCode(){
return this.id;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
Student xiaoMing = new Student(1,"小明");
//故意把小亮學號設成小明的,作爲異常數據,不應該發給他學生卡
Student xiaoLiang = new Student(1,"小亮");
students.add(xiaoMing);
students.add(xiaoLiang);
Map<Student, SchoolCard> match = new HashMap<>(16);
students.stream().forEach(
student -> {
if (!match.containsKey(student)) {
match.put(student, new SchoolCard());
}
}
);
System.out.println(match);
}
}
程序運行輸出結果:
{Student{id:1;name:小明}=SchoolCard@4f3f5b24}
如果註釋掉Student類中equals和hashCode兩個方法中的任意一個,程序就會輸出如下:
{Student{id:1;name:小亮}=SchoolCard@7b23ec81, Student{id:1;name:小明}=SchoolCard@6acbcfc0}