在java的开发之中,我们经常会用到一个类,它就是HashMap,用来存储带有键值关系的数据,其中键是不相同的,值可以相同。
那么HashMap中到底放的是什么数据结构呢?我们打开源码进行查看。发现了放的是Node<K,V>节点。
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;
}
}
我们发现了存储的数据就是Node节点。那么节点是怎么保存的呢?
transient Node<K,V>[] table;
通过查看源代码,发现了这是个数组,用数组来存储了一系列的Node节点。
有数组,数组的元素有指向下一个Node的指针,我们可以推测出可能是下图所示的数据结构。
但我们没办法证明,这时候我们应该查看一下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数组,我们刚才讨论过。
Node<K,V> p;//p是通过hash算法算出来的下标上的Node节点,也就是头结点。
int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
//resize是扩容,等下讲解。这里就是数组还没有先搞个数组出来。
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
//表示这个数组上还没有节点,tab[i]就是我们这个新节点。
tab[i] = newNode(hash, key, value, null);
else {
//表示这个数组上有元素了,自然是往后面添加
Node<K,V> e; K k;
//下面就是把放在数组里的头结点用e保存起来
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;
}
下面我们重点分析一段
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
这个n是现在Node数组的大小这个hash是键的hash,方法如下。i是Node数组的位置,我们的这个键值对就是放在这个数组或者跟在这个数组所代表的链表上。这个要说明一下,key相同key.hahsCode一定相同,key1.hashCode()等于key2.hashCode(),key1不一定与key2相同,所以我们才能把不同的键放在一条链上。(n-1)&hash确定了这个值不会大于数组的长度,因为与运算的值取小。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
添加我们了解了,看下怎么获取。首先我们猜测一下,根据这个数据结构应该是先计算一下你的key的hashcode,定位到那条链表上,遍历链表,键相同了就返回这个node的value(Map就是用键来取值)。
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) {
//这里我们的first就是在数组里面的头结点
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 {
//通过循环检测我们的键是否和链表中的一个Node的键是相同的
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
//好的我们找到了这个节点,返回去。
return e;
} while ((e = e.next) != null);
}
}
return null;
}
这就完成了对一个节点的查询方法,我们也可以看出jdk开发人员是非常严谨的,用了这么多判断来确保数据结构的安全性。
下面讲解一下扩容。在讲解方法之前我们分析几个常量。
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;//这是我们map初始化大小,为16,这个确定了我们的Node数组大小,你只要初始化了,至少就有16个元素的数组就出现了。
static final float DEFAULT_LOAD_FACTOR = 0.75f;//这个叫做扩容因子,你扩容并不是等到装不下了才扩容,而是当你的元素超过了(最大值*扩容因子)时就扩容了,扩容因子越大表示散列表的装填程度越高,反之愈小,我们也不必关心什么时候最好,毕竟jdk人员写的,考虑的肯定很深了。
好了,可以谈谈方法了,扩容就是到负载量了(最大值*扩容因子),我们把数组扩大一下,毕竟如果有一条链非常长的话,无论是添加还是查找都会变得很慢(O(n)),但是我们找的数据大多都在头结点,头结点是数组,那么就是(O(1))。所谓扩容就是把数组扩展两倍,把原来的长链拆成两条。一条变两条是确定了,而且一定是两条,这和它的算法有关,分析完方法后会详细解释。
final Node<K,V>[] resize() {
//老数组先保存一下
Node<K,V>[] oldTab = table;
//老数组的大小
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//老的扩容量阈(yu四声)值
int oldThr = threshold;
//新数组的大小和新的阈值
int newCap, newThr = 0;
if (oldCap > 0) {
//老数组已经都要超过最大值了,就不扩容了
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
// <<1就是乘2,下面就是针对不同情况来进行不同的扩容方式,目的就是得到新数组
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就是我们的新数组了。
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;
//用来判断相较于以前是否发生了位置变化,oldCap表示成二进制是
//1000000....之前我们计算位置用的是table.length-1也就是
//11111111...这样的计算就可以保证,具体的操作还是自己慢慢推吧。
if ((e.hash & oldCap) == 0) {
//高位的两个对象指向e
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
//低位的两个指针指向e表示换位置了
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;
}
常用的方法大概就这些了,关于红黑树操作问题,我会在我的下一篇中讨论。