文章目录
一 数据结构
数组+链表/红黑树,红黑树是java8的改进。
二 使用场景
HashMap是非线程安全的,所有多个线程同时写入会有问题,适用于单线程写,多线程读的场景。
ConcurrentHashMap可以解决线程安全的问题。
三 常量 变量含义
// 默认初始容量 16,2的4次方
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
// 最大容量,2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30;
// 装载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
final float loadFactor;
// 取值是:(int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
// 当 ++size>threshold 时,会进行扩容
int threshold;
// 当链表长度大于8,链表会变成红黑树
static final int TREEIFY_THRESHOLD = 8;
四 代码分析
1 数据存储结构
是一个Node的数组
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, <font color=red> length is always a power of two.</font>
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
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;
}
}
如何处理冲突?
HashMap使用链接法,当链表长度大于8会升级为红黑树。
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;
// i = (n - 1) & hash获取数组下标,并且所在下标没有数据
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 {
// 这里遍历链表,超过TREEIFY_THRESHOLD,变换成红黑树,找出要插入(这里是链表结尾)还是更新
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;
}
怎么扩容?高效实现数据迁移?
这里扩容的过程是rehash,自然而然要涉及到数据迁移。比较简单的方案是,数组扩大一倍,然后计算每一个元素新的位置进行调整,但是这样效率很低。
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;
}
// 这里翻倍了,新的newCap = oldCap << 1,这里很关键
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
// 这里是链表数据高效迁移,是一整套设计。
// 首先newCap = oldCap << 1,新的容量总是老的两倍,并且总是2的倍数
// 老的节点去计算索引时,总是在 原地 或者 newTab[j + oldCap]
// 这个设计真的很巧妙
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;
}
在HashTable中,initialCapacity的默认值是11,取了素数。而HashMap没有取素数,而是取了合数,并进行了一整套的设计,更高效。
五 hash表知识
hash 冲突
链接法chaining
最坏的情况 是所有节点都到了 一个链表里面,时间复杂度O(n)
开发寻址法open addressing
- 线性探查
- 二次探查
- 双重散列
完全散列 perfect hashing
散列函数
除法散列法
h(k) = k mod m
乘法散列法
h(k) = m(kA mod 1) 0<A<1,取kA mod 1的小数部分
全域散列法
public class MyHashMap1 {
private Node[] items;
private int capacity;
public MyHashMap1(int capacity) {
items = new Node[capacity];
for (int i = 0; i < capacity; i++) {
items[i] = null;
}
this.capacity = capacity;
}
public Node get(Object key) {
int i = 1;
while (true) {
int j = doubleHashing(key.hashCode(), capacity, i);
if (items[j] != null) {
return items[j];
}
if (i + 1 > capacity) {
return null;
}
i++;
}
}
public Object put(Object key, Object value) {
int i = 1;
while (true) {
int j = doubleHashing(key.hashCode(), capacity, i);
if (items[j] == null) {
items[j] = new Node(key, value);
return items[j];
}
if (i + 1 > capacity) {
return -1;
}
i++;
}
}
public Object remove(Object key) {
return null;
}
/**
* 除法散列法
*/
public int h1(int k, int m) {
return k % m;
}
/**
* 乘法散列法
* 0 < A < 1
*/
public int h2(int k, int m, float A) {
return (int) (Math.random() * m);
}
/**
* 全域散列法
* p是素数
*/
public int h3(int k, int p, int m) {
int a = 11, b = 13;
return ((a * k + b) % p) % m;
}
/**
* 线性探测
*/
public int linerProbing(int k, int m, int i) {
return (h1(k, m) + i) % m;
}
/**
* 二次探测
*/
public int quadraticProbing(int k, int m, int i) {
int c1 = 17, c2 = 67;
return (h1(k, m) + c1 * i + c2 * i * i) % m;
}
/**
* 双重散列
*/
public int doubleHashing(int k, int m, int i) {
return (h3(k, 17, m) + i * h1(k, m)) % m;
}
class Node {
private Object key;
private Object value;
public Node(Object key, Object value) {
this.key = key;
this.value = value;
}
public Object getKey() {
return key;
}
public Object getValue() {
return value;
}
}
public static void main(String[] args) {
MyHashMap1 myHashMap1 = new MyHashMap1(3);
// hash函数好像有问题,还需调试
// myHashMap1.put(1, 1);
myHashMap1.put(2, 2);
myHashMap1.put(3, 3);
System.out.println(myHashMap1.get(1).getKey() + " : " + myHashMap1.get(1).getValue());
}
}