一. 第一次添加元素时,代码如图
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> set=new HashSet<>();//创建HashSet对象,调用了该类中无参构造方法,执行了该构造方法中map = new HashMap<>();
set.add("Tom");//思考:如何添加进去的?
}
}
先分析add方法
点击add,长按Ctrl键点进去,如图所示
可见返回的是一个map的方法,map为HashSet全局变量,map指向的是创建HashSet对象时创建的HashMap对象,所以调用了map的put方法,再分析put方法,点进去如图所示
先分析Hash方法,源代码如图所示,其中key就是开始输入的"Tom".
刚开始key是"Tom",不是null,所以执行h=key.hashCode()
HashCode源代码如图
native是本地方法
hashCode()是对象的地址
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.hashCode());
System.out.println(Integer.toHexString(test.hashCode()));
System.out.println(test);//默认调用toString方法
System.out.println(test.toString());
}
}
执行如图所示代码,输出结果如图所示
实质上,ToString()方法与HashCode方法返回的是相同的地址,只不过是ToString方法对HashCode进行了加工(变成了16进制)
总结:不同对象的hashCode一定不相同;相同对象的HashCode的值一定相同。
所以HashMap中hash方法:传入相同的对象,得到相同的结果
下面重点分析putVal方法(判断add是否重复)
putVal方法中的源代码如图所示:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab;//创建一个名为tab的NODE数组
Node<K,V> p;
int n, i;
if ((tab = table) == null || (n = tab.length) == 0)//table为全局变量,指向一个为空的Node数组
//tab和table指向同一个地址,所以(tab = table) == null为true,执行if
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)//n为16,i的值跟Hash有关,即不同的Hash对应不同的值,因为此时tab为null,所以执行if中的语句
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;
}
}//执行完上一个if,直接到这里,返回null
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
key即为传入的“Tom”,putVal返回null之后,返回上一步put方法可知,put也返回Null,则add返回true,"Tom"添加成功。
二.当再次添加相同的元素时,代码如图
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> set=new HashSet<>();
set.add("Tom");
set.add("Tom");
System.out.println(set.size());
}
}
输出结果:1
思考:程序怎么判断所添加元素是否重复?
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)//第二次table不等于null,所以跳过该if语句
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;//if满足条件,故执行此行代码
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) { //执行到这里,e=p不为空,继续执行
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)//onlyIfAbsent默认值为false,故条件成立,继续执行
e.value = value;
afterNodeAccess(e);
return oldValue;//返回值不为null,则put返回值不是null,则add添加失败
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
三.当添加不同的元素时,代码如图所示
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> set=new HashSet<>();
set.add("Tom");
set.add("Jim");
System.out.println(set.size());
}
}
此时输出结果为2
程序是如何添加不同的元素的呢?
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)//第二次赋值时,table不等于null,所以跳过该if语句内容。
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)//因为第二个Jim的hash与第一个Tom的hash不同,所以执行该if语句内容。
tab[i] = newNode(hash, key, value, null);//将key为Jim,value为一个Object常量,即相对应的hash赋值给tab[i]。以下else不执行。
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,直接到这里,该putVal方法返回null,结束该方法。
}