力扣题
这道题在力扣上有设计哈希映射。想过的话,很简单,按照哈希表的设计原理,设计一个简易的HashMap
类就好。
一个简易的HashMap
需要支持三个方法:
void put(K key, V value)
V get(K key)
void remove(K key)
为了实现哈希节点链表数组,还需要指定数组的容量capacity
和设计节点类HashNode
。下面是我这道题的答案【很简陋】:
class MyHashMap {
int capacity;
HashNode[] hashList;
public MyHashMap() {
this.capacity = 1000;
this.hashList = new HashNode[this.capacity];
}
public void put(int key, int value) {
int i = key % this.capacity;
HashNode node = this.hashList[i];
HashNode pre = null;
while (node != null && node.key != key) {
pre = node;
node = node.next;
}
if (node == null) {
if (pre == null) {
this.hashList[i] = new HashNode(key, value);
} else {
pre.next = new HashNode(key, value);
}
} else {
node.value = value;
}
}
public int get(int key) {
int i = key % this.capacity;
HashNode node = this.hashList[i];
while (node != null && node.key != key) {
node = node.next;
}
if (node == null) {
return -1;
} else {
return node.value;
}
}
public void remove(int key) {
int i = key % this.capacity;
HashNode node = this.hashList[i];
HashNode pre = null;
while (node != null && node.key != key) {
pre = node;
node = node.next;
}
if (node != null && pre != null) {
pre.next = node.next;
} else if (node != null) {
this.hashList[i] = node.next;
}
}
}
class HashNode {
int key;
int value;
HashNode next;
public HashNode(int key, int value) {
this.key = key;
this.value = value;
}
}
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/
Java源码(JDK14)
实现一个简易哈希表就这么简单,但是Java源码是如何实现它的值得我们深究,下面解析一下官方代码【完整源码见官方文档,这里只挑重要的说明】:
HashMap类注释
- 哈希表基于
Map
接口实现,提供了所有可选的map操作,允许null
值和null
键。 HashMap
和Hashtable
大致等同,唯一区别是前者线程不同步,且允许空值空键。HashMap
是无序的,内部顺序可能随着时间变化。get
和put
的时间复杂度是常数时间的。- 如果在乎迭代性能,切记不要把初始容量设置太大,也不要把装载因子设置太小。
- 哈希表会在条目数超过装载因子*当前容量时发生重哈希(rehash)和扩容(至原来的2倍)。
- 装载因子的默认值是0.75,是时间性能和空间代价的折中。更高的值会降低空间代价,但会带来更高的查询代价。
- 谨记:
HashMap
是线程不同步的。如果多线程同时操作一个hashmap,并且至少有一个线程结构化地修改了hashmap,那么它必须被显式同步synchronize
。结构化地修改具体是指插入或删除一个映射,仅仅是该表一个已有键的值并不算结构化修改。实际中最好将HashMap·封装到线程安全类中,比如
Collections.synchronizedMap`是一个很好的工具。 - 不要在遍历
HashMap
的时候结构化的修改它(增加或删除)。
类声明
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
具体实现的注释前言
HashMap
通常是一个桶哈希,但是当桶太大时,太大的桶会转化成树,每个桶就类似于TreeMap
的实现。当树变小的时候,又会退化成桶。- 理想状态下,桶中节点的频率服从泊松分布(参数平均为0.5,在默认装载因子为0.75的情况下)。忽略方差的影响,每个位置发生碰撞时,那么这个位置的链表数大于等于8的概率小于1/1000000,因此,将装载因子设置为0.7~0.75(默认值)之间。
重要的成员变量
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
默认初始容量,必须是2的幂次。static final int MAXIMUM_CAPACITY = 1 << 30;
最大容量,2的幂次。static final float DEFAULT_LOAD_FACTOR = 0.75f;
默认装载因子static final int TREEIFY_THRESHOLD = 8;
树化的桶大小阈值static final int UNTREEIFY_THRESHOLD = 6;
桶化的树大小阈值,仅用于resize发生时,重哈希导致某些位置的树节点变少,低于此阈值时退化成桶static final int MIN_TREEIFY_CAPACITY = 64;
最小的树化的容量阈值,。应该至少为TREEIFY_THRESHOLD
的4倍。否则会引发resize和树化的冲突。
桶节点类
非常简单,都是一些Object
的方法。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
hash
函数
HashMap
中在计算键的哈希值时,使用了这个函数:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
可以看到,他并没有直接使用key.hashCode()
作为键的哈希值,而是将其hashCode()
的高16位和低16位做了异或,再作为键的哈希值,这种操作叫做扰动函数。
之所以在哈希时需要扰动,是因为Object.hashCode()
会得到一个32位的int
值,这个值在int
空间中是松散的,但不见得在HashMap
中是松散的(因为容量是有限的,如默认16)。在HashMap
的键空键中,假设容量为16,则会只取hashCode()
的低4位,这有可能会发生很严重的碰撞。但是,如果把hashCode()
的高16位,拉下来和低16位做一个异或,那么就扰动了32位的信息,从而能够降低碰撞的风险。
成员变量
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
transient int size;
transient int modCount;
(结构化)修改计数器int threshold;
扩容阈值(容量*装载因子)final float loadFactor;
装载因子
构造器
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
其中,阈值threshold
的获取是用这个函数,这个函数利用了位运算,非常高效,给定一个数cap
,输出不小于cap
的最小2的幂次数。
static final int tableSizeFor(int cap) {
int n = -1 >>> Integer.numberOfLeadingZeros(cap - 1);
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
Size()
和isEmpty()
返回哈希表的大小,没什么好说的
public int size() {
return size;
}
判断是否为空
public boolean isEmpty() {
return size == 0;
}
get
方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
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;
}
get
方法首先要调用hash()计算key的哈希值,再通过getNode
方法获取key对应的节点,如果节点不为空,则返回value值。其中hash()
函数做了扰动处理,对key.hashcode()
的高16位和低16位做异或(不同jdk版本的实现方案不同)。
仔细看getNode
的实现细节,有几点:
- 判定首要条件:哈希表不为空 && 哈希表的长度不为0 && 哈希表中hash对应桶的第一个元素不为空。
- 计算
hash % (n-1)
时,用位运算加速hash & (n-1)
hash % (n-1)
用来定位桶,hash
用来比较key
是否相同。- 总是先检查每个桶的第一个节点
first
,如果是要获取的键,则返回first
。 - 节点
e
是目标节点的判断条件是e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))
。注意,需要同时满足hash相同和key相等。hash值是调用Object.hashcode()
方法获取的,而key相等包括内存相等或equals()
方法相等,因此,如果要实现自定义类的HashMap功能,需要设计好自定义类的hashcode()
和equals()
,缺一不可。 - 如果
first
节点是树状节点,则执行树状搜索方法getTreeNode()
。
put
方法
put
方法调用了putVal
方法来实现插入更新。需要注意的有:
- **
put
方法是有返回值的。**如果put
是插入,则返回null
,如果是更新,则返回旧值。 resize()
方法用来初始化table
或扩张原table
,详见下文。- 如果哈希表为空,或长度为0,则调用
resize()
初始化。 - 如果
hash%(n-1)
对应的桶的第一个元素为空,则在这个位置上新建一个节点。 - 3和4均不满足,则进入到桶链表中搜索。搜索条件仍是hash值相同且key相等。如果第一个节点为目标节点,则记录之;否则如果第一个节点是树状节点,则转到树状节点插入
putTreeVal
;否则,对桶链表遍历,如果有满足条件的节点,则记录之,否则,插入新节点,且判断此时位置是否超过树化阈值,如果超过,则执行树化逻辑treeifyBin()
。 - 如果找到了目标节点,则执行更新逻辑。
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;
}
至于resize()
方法,无非就是新建一个更大的(2倍于原来的)哈希表,并把原来的桶链表用新的哈希函数(原来是hash%(oldCap-1)
,现在是hash%(newCap-1)
)打散到新的哈希表中。如果原来是树状的,则需要调用节点的split
方法对树分割。代码稍长,不做具体分析了。
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
remove
方法
remove
方法和put
方法就大同小异了,一个是定位节点修改(或插入),一个是定位节点并删除。
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
clear()
clear()
非常简单粗暴,对每一个桶,直接做null
赋值。
publicvoid clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
containsKey
方法
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
调用getNode
找到和key
对应的节点,不为空则存在。
containsValue()
如果你把哈希表比作一个二维节点矩阵的话,哈希表存储每一个桶链表的指针,那么判断值是否存在其实是一个双层遍历,没有加速操作,复杂度是O(n^2)
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
for (Node<K,V> e : tab) {
for (; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
HashSet
至于HashSet
的源码实现,则是完全用HashMap
来代替的,插入元素时,哈希表的值设置为一个哑对象: