直接进入正题,HashSet是Java集合Set的一个实现类,功能十分的强大,但为了更好的使用,我们需要解析源码,我看了老韩(韩顺平老师)的视频,结合自己的理解,以一个小白的视角,部分的解析了HashSet源码,在看此之前先需了解hashSet表层的运行机理
废话不多说,直接上代码
package com;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/**
* @author HKS
* @version 1.0
*/
@SuppressWarnings({"all"})
public class HashMap_ {
public static void main(String[] args) {
HashSet hashSet = new HashSet();//断点1
hashSet.add("java");//断点2
System.out.println("hashSet = "hashSet);
}
}
以上就是一个简单的hashSet的实例化,然后使用了add方法,都十分的简单,但这简单的几行代码,背后确隐藏了很复杂的运行机制,我分别在main函数里下了两个个断点,然后就开始解析咯~
断点1
首先是断点1,我们在断点1追入源码(focus step into)
public HashSet() {
map = new HashMap<>();
}
我们发现在创建HashSet时,底层就是调用HashMap,解析HashSet就相当于部分的解析HashMap
断点2(重点)
继续追入(focus step into)
public boolean add(E e) { //E泛型,传入的是String
return map.put(e, PRESENT)==null;
PRESENT = new Object();
}
首先看PRESENT的定义
private static final Object PRESENT = new Object();
可以注意到PERSENT的定义是static final Object 说明大家都共用一个value
表明当前添加的元素是否出现了重复,假如第一次存放,put返回是null,add返回是true;元素重复,则put返回一个present对象,add返回false。
对于PERSENT的理解我就是到这里了,更加深入的理解我还不知道,这里暂时跳过,不影响
然后我们再追入put
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
这里的值都是key 传进去的就是java,value就是上面所说的公共对象
再追入hash(key)
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
这里就出现了一个计算哈希值的重要算法
(h = key.hashCode()) ^ (h >>> 16)
通过这样的一个计算得到我们的哈希值,可以看出哈希值就由hashCode经过计算得出的,但hashCode并不是哈希值
然后返回出来我们追入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)
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;
}
代码量有点多,我们逐步解析,首先看到
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
table表一开始就为空的,因为还没创建,这很容易理解
于是我们在追入resize(),简单来说这里就是对表的创建(难中难点!!!)
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;
}
这里也代码量有点多,我们先看
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);
}
一开始oldCap默认就是0,所以这一通判断,执行的就是
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
DEFAULT_INITIAL_CAPACITY代表的就是初始容量,为1 << 4 = 16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
DEFAULT_LOAD_FACTOR为默认加载因子默认值为0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
所以newCap为初始容量,newThr为扩容缓存
意思是不用等到满16再扩容,只要到达了加载因子乘以总容量0.75 * 16 = 12就扩容
然后就是这三段十分关键的代码
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
根据容量创建了table
创建好table后就返回出去
于是我们回到putVal()
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
此段代码就把String内容是"java",写入table
有兴趣的可以继续追入newNode,但可能要耗费一功力哈哈哈
最后计数加一后返回null
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
返回null时boolean判断,就为true,否则为false,再看回add函数
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
最后再来看看如果加入计算出哈希值相同时源码是怎么操作的,上代码
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;
}
}
首先判断调用equals(可重写,程序员自己定)方法后,是否相同(有时有可能内容不同但哈希值就是刚刚好相同了)
key != null && key.equals(k)
如果不是直接赋值,如果是再判断是否为一课树
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
如果是的话,就按照树的处理方式,调用putTreeVal,否则就只剩一种情况了,很可能就是链表了
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;
}
如果是链表的话,就先for循环判断,插入的元素是否为链表里的元素,如果是,则直接跳过不插入,如果不是,则直接插入尾端
部分解析到这里就结束啦,博主暂时能力有限,正深造中,更深入的解析后续更新 ~