哈希表(Hash table)
简介
- 哈希表,也叫散列表,是根据关键码值(key value)直接进行访问的数据结构。
- 哈希表通过关键码值映射到表中的一个位置来访问记录,以加快查找的速率。
- 这个映射函数叫做散列函数(Hash Function),存放记录的数组叫做哈希表(散列表)。
工程实践
- 电话号码簿
- 用户信息表
- 缓存(LRU Cache)
- 键值对存储(Redis)
哈希函数(Hash Function)
哈希碰撞(Hash Collisios)
- 哈希碰撞:不同的数据经过哈希函数之后得到相同的值,产生碰撞。
- 解决方法:拉链式解决冲突法。在同一个位置拉一个链表来进行存储。若在同一位置堆积很多值,即这个链表很长,这个时候的查询时间复杂度会退化到O(n)。
- 哈希表的查询复杂度为O(1),最坏情况为O(n)。
- 好的哈希函数会尽量少产生碰撞,但是当产生碰撞时,可以使用拉链式解决方法。
Java中的哈希表
Set的实现分为:HashSet和TreeSet
- HashSet通过HashMap来实现。在存储时将元素放进HashMap的key位置上,生成一个占位放在value位置上。
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
- TreeSet通过红黑树来实现(待补)
Map的实现:HashMap和TreeMap
- 通过HashMap实现
常量与变量
// 默认初始容量必须是2的幂,这里是16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量(必须是2的幂且小于2的30次方,如果在构造函数中传入过大的容量参数将被这个值替换)
static final int MAXIMUM_CAPACITY = 1 << 30;
// 默认负载因子,啥叫负载因子呢,HashMap通过负载因子与桶的数量计算得到所能容纳的最大元素数量
// 计算公式为threshold = capacity * loadFactor
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 链表转化为红黑树的阈值
static final int TREEIFY_THRESHOLD = 8;
// 红黑树转化为链表的阈值,扩容时才可能发生
static final int UNTREEIFY_THRESHOLD = 6;
// 进行树化的最小容量,防止在调整容量和形态时发生冲突
static final int MIN_TREEIFY_CAPACITY = 64;
hash()
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
当key为null时直接返回0,key的hash值高16位不变,低16位与高16位异或作为key的最终hash值。如此设置的原因是因为下标的计算是:n = table.length; index = (n-1) & hash;
table的长度都是2的幂,因此index仅与hash值的低n位有关,hash值的高位都被与操作置为0了,所以异或降低冲突。
getNode()方法 :
public V get(Object key) {
Node<K,V> e;
//求出key的hash值,调用getNode
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* 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;
//当table不为空,且计算得到的查询位置table[i]也不为空时继续
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
//判断table[i]的首个元素first是否等于key,若相等直接将其返回
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 {
//如果存储结构是链表,则遍历链表,找到key所在位置
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
putVal()方法
public V put(K key, V value) {
//求出Key的值,并直接调用putVal
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods.
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//1.如果table为空或者length为0,则调用resize扩容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//2.根据Key的hash值得到插入的数组索引i,如果table[i]为空,直接直接新建结点进行插入即可
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//如果table[i]不为空
else {
Node<K,V> e; K k;
//3.判断table[i]的首个元素是否等于Key,若等于直接覆盖value
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//4.判断table[i]是否为treeNode,即它是否为红黑树,如果是直接在树中插入键值对
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//5.遍历table[i]
for (int binCount = 0; ; ++binCount) {
//若链表长度小于8,则执行链表的插入操作
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//若链表长度大于等于8,则将链表转换为红黑树,执行插入操作
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//在遍历过程中,如果发现Key已存在则直接覆盖value
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//Key已存在,用新的value覆盖原来的value,返回旧的value
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//modCount+1,用来实现fail-fast机制
++modCount;
//插入成功后,判断实际存在的键值对数量size是否超过最大容量threshold,如果超过调用resize扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
- TreeMap通过红黑树来实现(待补)