一、hash方法
执行add()方法之前,应该先清楚hash()方法的执行规则
package demo;
import java.util.HashSet;
public class Test {
static int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); //如果输入的对象不为空则调用传入对象的hashCode()方法,返回计算的结果
}
public static void main(String[] args) {
HashSet<String>set = new HashSet<>();
set.add("tom");//HashSet 存储的数据实质存在了HashMap的key
int hash=hash("tom");
System.out.println(hash);
hash=hash(new String("tom"));
System.out.println(hash);
hash=hash(10000);
System.out.println(hash);
hash=hash(new Integer(10000));
System.out.println(hash);
hash=hash(new Student());
System.out.println(hash);
Student student = new Student();
hash=hash(student);
System.out.println(hash);
hash=hash(student);
System.out.println(hash);
}
}
class Student{
}
执行结果
115027
115027
10000
10000
5433712
2430314
2430314
分析:若为String类型:如果内容相同,则返回值相同
若为基本数据类型包装类:如果值相同,则返回值相同
若为自定义类型:如果地址不同,则返回结果不同
二、add()方法
public static void main(String[] args) {
HashSet<String>set = new HashSet<>();
set.add("tom");//HashSet 存储的数据实质存在了HashMap的key
set.add("tom");
set.add("lulu");
}
点击进入add方法
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
add方法中的变量传入到参数e中,PRESENT是一个常量
点击put进入
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
e和PRESENT分别传入key和value中,所以HashSet存储的实质是存储进HashMap的key
再点击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;
}
上一步中的hash(key),key,value,false,true分别传入到int hash,K key,V value,boolean onlyIfAbsent,boolean evict中
即add方法的执行过程是:HashSet中的add方法到HashMap中的put方法再到HashMap的putVal方法。
当执行第一个set.add(“tom”)语句时:
第一步:执行if ((tab = table) == null || (n = tab.length) == 0)判断,第一次add时,table数组为空,执行if语句内部代码tab=resize()给tab一个数组空间,table为全局变量,tab和table指向同一个数组;
这里的resize()返回的值为默认的长度为16,并把resize()赋给tab,resize()和tab指向的同一个对象(后文中阐述);而table也赋值给tab.所以他们三个指向同一对象
第二步:执行(p = tab[i = (n - 1) & hash]) == null)判断;这里通过把表达式((n - 1) & hash)结果赋给i,可以找tab[i]的值,判断tab[i]是否为null,如果为空就把"tom"对象存进去.,同样的table作为全局变量指向的对象,就把"tom"对象存入了;
第三步:执行如下代码
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
由于上面的代码执行了if的语句所以不执行else部分,返回null
为什么resize()和tab指向同一个对象?
分析下边代码:
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;
}
分析可知,代码最后部分的return newTab语句一定会被执行,所以resize()方法的返回值就是newTab指向的对象,所以tab和resize()指向的就是同一个对象
当执行第二个set.add(“tom”)语句时:
第一步:执行if ((tab = table) == null || (n = tab.length) == 0);此时tab与table指向同一个数组,table为全局变量,且table中已经有元素(上一语句执行成功的结果),此次if中语句未成立,跳过执行后边的代码;
第二步:执行(p = tab[i = (n - 1) & hash]) == null)
此时的hash和上一步的hash值一样,所以这里的i和第一个tom的i相同,table[i]里不为null,此时该if语句内未成立,跳过执行后边的代码;
第三步:跳转到else语句
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
这里的p.hash为第一个tom的hash,与后边的第二个tom的hash值相同,返回true;而第一个tom的地址和第二个tom的地址相同,所以也为true;即&&判断成功,此处把第一个tom的地址赋给e;
第四步:执行下列代码
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
e不为空所以执行if语句中的内容,返回第一个tom的值
此时应该清楚,第二个tom为什么没有被存进去了,也可以知道HashSet中不可以存储重复数据
当执行set.add(“lulu”)语句时
第一步:执行if ((tab = table) == null || (n = tab.length) == 0);此时tab与table指向同一个数组,table为全局变量,且table中已经有元素,此次if中语句未成立,跳过执行后边的代码;
第二步:执行(p = tab[i = (n - 1) & hash]) == null)判断并通过(n - 1) & hash计算下标,hash=hash(‘lulu’),tab[i]为null,if语句成立,执行tab[i] = newNode(hash, key, value, null);新建一个Node对象存到tab中。
第三步:跳过else执行
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
返回null;