1.HashMap数据结构
首先先看下HashMap的数据结构图
我们都知道数组的储存方式在是连续的,查找速度比较快,但插入和删除数据比较慢
而链表的存储方式是非连续的,所以插入和删除速度较快,但查找速度就比较慢,HashMap在数据结构上两种都采用了。
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
再看下Node中的变量 (Node中含有hash值、key、value以及指向下个节点的next)
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;
}
通过这个table变量我们就能理解上面那个数据结构图,它不仅使用了数组,而且还采用了链表结构。
2.HashMap变量
首先我们看下HashMap中的变量,在看之前思考几个问题:
1. HashMap数据结构既然使用了数组,那么数组默认内存大小是多少?
2.当已使用内存大小超过总内存的一个百分比后,需要继续增大内存,这个百分比是多少?
3.当链表节点长多超过多少时储存结构变成红黑树?
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
由此可以知道数组的默认大小是16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
当数组不够大的时候,就会增加内存大小,大小的上限为1<<30,也就是2的30次方
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
这个变量就是问题2的答案,也被称为负载因子,默认为0.75
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
这个变量就是问题三的答案,当节点数量超过8时,储存结构转换成红黑树
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
当bin的个数小于6时由树形结构调整为列表
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
当前HashMap中储存key-value的大小
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;
HashMap被修改和删除的次数
3.HashMap的储存过程
HashMap hashMap = new HashMap();
hashMap.put("1","1230");
System.out.print(hashMap.get("1"));
我们从hashMap.put()方法开始
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
这里详细讲下hash()函数,首先先看源码:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
如果key的值不为空的话,就把变量h等于key值的hashCode,然后把h的高16位与低16位进行一个异或运算,这样得到的值和数组的默认长度16相对应,方便后续计算该Node存储的数组下标是多少。
然后回到putVal()方法
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)//初始化tab
n = (tab = resize()).length;//n为数组总长度
if ((p = tab[i = (n - 1) & hash]) == null)//i为储存的数组下标
//传入的hash值与数组长度进行位与运算,这样就可以保证数值不越界,得到结果赋值给i,
//如果i处为空的话,就把node储存到该下标
tab[i] = newNode(hash, key, value, null);
else {//如果下标i处存有值的话,就使用链表结构,此时p=tab[i]
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;//key值存在的话,就不存
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;
}
未完。。。。待续