寫這篇文章起源于一道面試題,如何將自定義的類對(duì)象作為key存儲(chǔ)到HashMap中,即考慮怎么判斷key的唯一性。
首先,我們看以下HashMap中put(...)方法的源碼:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
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;
}
關(guān)注插入判斷的這一行代碼:
if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))
可以看到HashMap是通過驗(yàn)證hashCode和key的相等兩個(gè)步驟保證key的唯一性的。
所以要想實(shí)現(xiàn)對(duì)象作為鍵插入,則需要重寫hashCode()和equals()方法,以下給出示例:
package com.zhangcf.hashmap;
import java.util.HashMap;
import java.util.Map;
class Student{
private String name;
private int age;
public Student(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
int result = 31;
result = result * 31 + age;
result = result + 31 + ((name == null) ? 0:(name.hashCode()));
return result;
}
@Override
public boolean equals(Object obj) {
return this.name.equals(((Student)obj).name) && (this.age == ((Student)obj).age);
}
}
public class HashMapTest {
public static void main(String[] args) {
Student student = new Student("jack",23);
Map<Student, Integer> map = new HashMap<>();
map.put(student, 1);
System.out.println(map.get(new Student("jack",23)));
}
}
這樣就保證了屬性相同的對(duì)象,即使不是同一對(duì)象也能存儲(chǔ)在同一個(gè)key里面。
在重寫以上兩個(gè)方法之后,有關(guān)hashCode和equals兩者的關(guān)系有這樣的說法:
對(duì)于兩個(gè)對(duì)象,
- 如果調(diào)用equals方法得到的結(jié)果為true,則兩個(gè)對(duì)象的hashcode值必定相等;
- 如果equals方法得到的結(jié)果為false,則兩個(gè)對(duì)象的hashcode值不一定不同;
- 如果兩個(gè)對(duì)象的hashcode值不等,則equals方法得到的結(jié)果必定為false;
- 如果兩個(gè)對(duì)象的hashcode值相等,則equals方法得到的結(jié)果未知。
在重寫hashCode函數(shù)時(shí),有以下規(guī)則:
hashCode函數(shù)的通項(xiàng)如下:
public int hashCode() {
int result = 17; //任意素?cái)?shù)
result = 31*result +c1; //c1,c2是什么看下文解釋
result = 31*result +c2;
return result;
}
其中c1,c2是我們生成的你要計(jì)算在內(nèi)的字段的代碼,生成規(guī)則如下:
- 如果字段是boolean 計(jì)算為(f?1:0);
- 如果字段是byte,char,short,int則計(jì)算為 (int)f;
- 如果字段是long 計(jì)算為 (int)(f^(f>>32));
- 如果字段是float 計(jì)算為 Float.floatToLongBits(f);
- 如果字段是一個(gè)引用對(duì)象,那么直接調(diào)用對(duì)象的hashCode方法,如果需要判空,可以加上如果為空就返回0;