HashMap键值对操作场景
首先探讨一个常见的面试场景:
当HashMap中存储了由自定义类型构成的键值对后,如果在外部修改了某个key的属性,随后再次使用该key尝试获取对应的value,此时HashMap会返回什么结果?
虽然文中已提供了示例代码及最终答案,但并未深入解释背后的HashMap底层原理。
一、特性分析
理论上可以使用任何类作为HashMap的键,但这些类需要满足特定的限制条件。参考以下代码逻辑:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
}
Map testMap = new HashMap<>();
testMap.put(new Person("hello"), "world");
testMap.get(new Person("hello")); // ---> null
原本期望取出字段值相等的Person类所对应的value,实际却得到了null。熟悉HashMap机制的人会发现——这是因为Person类没有重写hashCode方法,导致其继承了Object类的hashCode实现(仅返回内存地址)。这也解释了为何String或Integer等不可变类常被用作HashMap的键。那么,HashMap究竟是如何利用hashCode为键进行快速索引的呢?
二、底层原理
首先参考《Thinking in Java》中提供的一个简易HashMap实现方案:
//: containers/SimpleHashMap.java
// A demonstration hashed Map.
import java.util.*;
import net.mindview.util.*;
public class SimpleHashMap extends AbstractMap {
// Choose a prime number for the hash table size, to achieve a uniform distribution:
static final int SIZE = 997;
// You can't have a physical array of generics, but you can upcast to one:
@SuppressWarnings("unchecked")
LinkedList>[] buckets =
new LinkedList[SIZE];
public V put(K key, V value) {
V oldValue = null;
int index = Math.abs(key.hashCode()) % SIZE;
if(buckets[index] == null)
buckets[index] = new LinkedList>();
LinkedList> bucket = buckets[index];
MapEntry pair = new MapEntry(key, value);
boolean found = false;
ListIterator> it = bucket.listIterator();
while(it.hasNext()) {
MapEntry iPair = it.next();
if(iPair.getKey().equals(key)) {
oldValue = iPair.getValue();
it.set(pair); // Replace old with new
found = true;
break;
}
}
if(!found)
buckets[index].add(pair);
return oldValue;
}
public V get(Object key) {
int index = Math.abs(key.hashCode()) % SIZE;
if(buckets[index] == null) return null;
for(MapEntry iPair : buckets[index])
if(iPair.getKey().equals(key))
return iPair.getValue();
return null;
}
public Set> entrySet() {
Set> set= new HashSet>();
for(LinkedList> bucket : buckets) {
if(bucket == null) continue;
for(MapEntry mpair : bucket)
set.add(mpair);
}
return set;
}
public static void main(String[] args) {
SimpleHashMap m =
new SimpleHashMap();
m.putAll(Countries.capitals(25));
System.out.println(m);
System.out.println(m.get("ERITREA"));
System.out.println(m.entrySet());
}
}
SimpleHashMap构建了一个用于存储键的哈希表,其哈希函数采用取模运算Math.abs(key.hashCode()) % SIZE,并使用链表法处理哈希冲突;buckets中的每个槽位存放具有相同(哈希后)索引值的Map.Entry,结构示意如下:

JDK中HashMap的实现原理与此相似,它同样采用链地址法的哈希表table来存储Map.Entry:
/**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
transient Entry[] table = (Entry[]) EMPTY_TABLE;
static class Entry implements Map.Entry {
final K key;
V value;
Entry next;
int hash;
…
}
Map.Entry的索引是通过对键的hashCode进行哈希计算后得出的。当执行get操作获取键对应的值时,系统会对键计算其索引,然后在table中定位并取出Map.Entry即可。具体逻辑可参考代码:
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
final Entry getEntry(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : hash(key);
for (Entry e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
由此可见,hashCode直接决定了HashMap哈希函数的效率——优质的hashCode能显著降低哈希冲突,从而提升查询性能。这也回答了开篇的两个问题:若使用自定义类作为HashMap的键,其hashCode的计算必须涵盖构造函数的所有字段,否则可能因哈希冲突或匹配失败而返回null。