目录
一.HashSet中对象的创建
在分析add方法的底层代码之前,先来分析一下HashSet集合对象是如何创建的。
以下代码创建了一个HashSet集合的对象,引入了HashSet的包,按住Ctrl键点击HashSet<>,进入底层代码:
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> set=new HashSet<>();
}
}
可以看到HashSet的构造方法的底层代码,其实质是创建了一个HashMap类集合的对象,将其赋值给了全局变量map:
public HashSet() {
map = new HashMap<>();
}
二.add方法中其他方法的分析
下面是add方法的调用,按住Ctrl键点击add:
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> set=new HashSet<>();
set.add("Tom");
}
}
进入add方法的底层代码后可以看到,add方法返回值为,用全局变量map(里面存的是HashMap类集合的对象)调用HashMap类中的put方法,再次按住Ctrl键点击put:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
可以看到put方法中调用了一个putVal方法,该方法的第一个参数传递的是一个参数为key的hash方法,该hash方法就是要分析的第一个方法。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
1.hash(Object key)方法
该方法的返回值是由一个三目运算符运算出来的,当传入的参数key,也就是最开始传入HashSet集合中的对象,等于空时则返回0,不为空时返回一个由按位异或运算符运算出来的数,这一串表达式中还包含一个参数key调用的hashCode方法,要想知道hash方法返回的值就要继续查看hashCode方法到底是什么,我们继续点进去探索:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
进入hashCode方法后发现该方法是一个由native修饰符修饰的没有方法体的方法,说明该方法是由底层的c语言来实现的,那么我们如何知道其作用是什么呢?我们来写段代码运行一下。
public native int hashCode();
以下是hashCode方法的使用及输出结果:
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
Test test=new Test();
System.out.println(test);
System.out.println(test.hashCode());
}
}
我们都知道Test类变量中存放的是堆中对象的地址,所以直接打印变量test的结果是一串地址,而hashCode方法的返回值是一串像地址一样的数字,我们用调用方法将这串数字转为十六进制,发现打印结果就是该变量中存放的地址:
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
Test test=new Test();
System.out.println(test);
System.out.println(test.hashCode());
System.out.println(Integer.toHexString(test.hashCode()));
}
}
上述结果可以看出,hashCode方法用于打印对象的地址。
但是当调用hashCode方法的对象是String类型时,有一点需要注意:
按理来说如果使用两种方式创建String类对象得到的字符串的地址是不相同的,但是调用hashCode方法的输出结果却是相同的:
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
String str1="Tom";
String str2=new String("Tom");
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());
}
}
这是由于在String类中重写了hashCode方法,至于具体的底层代码就不做分析了,只需要记住两个String类型的字符串就算地址不相同,但是只要字符串相同,那么hashCode的返回值就相同。
这时我们再回到hash方法中来,可以得知该三目运算符中其实返回值是一个由参数key的地址决定的一个动态的运算式子,至于其在add方法中具体起什么作用我们后续再分析。
分析完hash方法,我们知道了put方法给putVal方法传入的第一个参数的内容了,接下来我们继续往下分析,按住Ctrl键点击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;
}
上面的底层代码的第5行还有一个陌生的resize方法,这就是我们要分析的第二个方法,要想知道putVal如何运行的就得先知道resize方法是干什么的。
2.resize()方法
进入resize方法的底层代码,不要被这个方法的代码长度吓倒了,我们目的是分析add方法,所以只需知道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;
}
我们先来看第28行和第29行,第28行新创建了一个Node<k,v>类型的数组newTab,第29行将该数组newTab赋值给了全局变量table,所以说执行完该resize方法后,全局变量table中存放的就是一个Node<k,v>类型的数组了。
我们再来看倒数第二行,该方法的返回值为newTab,正是新创建的Node<k,v>类型的数组,也就是说执行完resize方法之后全局变量table和该方法的返回值是同一个Node<k,v>类型数组的同一个地址值。
还有一点要注意到,那就是该数组的长度,在第28行中创建时显示长度为newCap,这时我们来看第18行,newCap被赋值为一个名为DEFAULT_INITIAL_CAPACITY的常量,按住Ctrl键点击该常量,查看到下面这行代码,所以该常量的值为16,也就是说resize方法返回的和全局变量table中的同一个数组的长度为16。
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
三.运行示例:
add方法中的其他方法分析过了,接下来就用几个示例来主要分析一下add方法。
1.传入一个String类字符串
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> set=new HashSet<>();
String str1="Tom";
set.add(str1);
}
}
当调用add方法向集合中添加一个字符串“Tom”时,先在add方法中调用HashMap中的put方法,传入两个参数,第一个是要添加的字符串“Tom”,第二个是一个常量不用管。
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
接下来再put方法中调用putVal方法,传入五个参数,第一个参数是调用hash方法的动态运算式计算出一个数,第二个参数是要添加的字符串“Tom”,第三个参数是那个常量不用管,四、五都是boolean型的值。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
接下来就来到了putVal方法:
第4行:先将全局变量table赋值给局部变量tab,但是由于是第一次往集合中添加元素,所以table变量中还是最开始的默认值null,所以该表达式的值为null,也就是说(tab = table) == null表达式的值为true,由于后面是逻辑或运算符,所以后面的表达式不需要看,该if判断条件为真,执行if代码块。
第5行:首先调用resize方法为tab赋值,刚才分析过resize方法的返回值为Node<k,v>类型数组,且在方法中为全局变量table赋值同一个数组,所以该表达式执行过后table和tab中存放的是同一个Node<k,v>类型数组的地址值;然后再取该数组的长度将其赋值给n,刚才分析resize方法时分析过该数组的长度为16,所以n的值被赋值为16。
第6行:首先将n-1也就是15与第一个参数hash进行按位与运算符,因为第一个参数hash是由hash(key)方法动态算出来的一个数,所以将其与15按位与之后得到的还是一个动态的数,再把这个数赋值给i后,将tab数组中的第i个结点赋值给p,因为这是第一次添加元素,所以数组中所有结点均为空,所以该if判断条件(p = tab[i = (n - 1) & hash]) == null成立,执行if代码块。
第7行:调用newNode方法将输入的元素赋值给tab数组的第i个结点。
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;
}
第37到40行:这些不在分析的范畴内,不用管它们。
第41行:返回null到上一级的put方法中。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
然后put方法再返回null到上一级的add方法中,得出该表达值为真,所以add方法返回true,字符串“Tom”元素添加成功。
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
2.传入第二个相同的字符串
既然HashSet集合中不允许字符串重复,那么我们就来分析一下它究竟是怎么实现这一功能的。
我们给该集合再添加一个“Tom”元素:
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> set=new HashSet<>();
String str1="Tom";
String str2="Tom";
set.add(str1);
set.add(str2);
}
}
前面的方法调用和上一次添加时一样,所以我们直接从putVal开始分析:
第4行:先将全局变量table赋值给局部变量tab,由于table是全局变量,所以里面存储的还是上一次添加元素时的那个数组的地址,数组里存储着上一次添加进去的那个元素,所以不为null,该表达式(tab = table) == null为false,再看逻辑或运算符后面的表达式,将tab数组的长度赋值给n,因为tab数组里存的是刚才table给赋的值,所以数组长度依然为16,不为0,所以表达式为false,if的判断条件不成立,执行第6行。
第6行:将n-1也就是15与参数hash进行按位与运算,因为刚才分析过String类中只要字符串相同,hashCode方法打印的数字便相同,而hash()方法中计算公式正是调用hashCode方法计算出来的,所以只要传入hash()方法的字符串相同,得到的数就是相同的,又因为hash参数是由hash(key)计算出来的,而这两次传入的key均为“Tom”,所以本次添加时的hash值和第一次添加时的hash值是一样的,所以计算出来的i值和第一次添加时的i值也是一样的,也就是说tab数组的第i个结点就是第一次添加元素的那个结点,因为里面已经有第一次添加的元素了,所以当然不为null,所以if判断条件不成立,执行第8行的else代码块。
第10、11行:首先这是一个逻辑与运算符,先看运算符前面的表达式,在第6行中已经把第一次添加的结点的地址赋值给了p,所以p.hash就是该结点的hash,而本次添加元素时计算出来的hash已经分析了和上次是一样的,所以逻辑与运算符前面的表达式为true;再看逻辑与运算符后面的是一个逻辑或表达式,逻辑或前面的表达式是将p结点的key值赋值给k,也就是第一次添加的“Tom”,而==后面的key是本次添加的“Tom”,等号运算符比较的是二者的地址,又因为二者都是直接赋值创建的对象,所以都是存储在堆中的常量池中,地址也是相同的,所以该表达式为真,逻辑或表达式也为真,前面的逻辑与表达式也为真,所以该if判断条件成立,执行if代码块。
第12行:p是第一次添加的结点,将该结点地址赋值给e。
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;
}
第29行:因为e中存储的是第一次添加的结点,不为null,所以if判断条件成立,执行if代码块。
第31行:onlyIfAbsent是该方法传入的第四个参数,由put方法传入的是一个false,所以逻辑非之后是一个true,由于该表达式是逻辑或,所以直接得出if判断条件成立,执行if代码块。
第32行:将第一次添加的结点中的value值覆盖为本次添加value,当然这在HashSet中无影响,因为value始终都是一个常量。
第34行:返回oldValue值,也就是第一次添加时的value常量,到上一级的put方法中,putVal方法结束。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
put方法再将该value常量返回给上一级的add方法,因为put的返回值不为null,所以add返回一个false,第二个字符串“Tom”添加失败。
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
3.两种创建String类对象的方式
刚才第二个示例中,添加的字符串“Tom”和第一次添加的相同,又因为二者都是直接赋值创建的对象,所以地址也是相同的。
而String类有两种不同的创建对象的方式,且创建的相同字符串的地址也是不相同的,那么此时add方法是如何实现不允许第二个“Tom”添加的呢?
以下是第二个字符串的添加:
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String> set=new HashSet<>();
String str1="Tom";
String str2=new String("Tom");
set.add(str1);
set.add(str2);
}
}
前面的方法调用和上一次添加时一样,所以我们直接从putVal开始分析:
第4行:和第二个示例的执行情况一样,不执行if代码块。
第6行:由于只要String类的字符串相同,参数hash的值便相同,所以执行情况和第二个示例也一样,执行第8行else代码块。
第10、11行:逻辑与运算符前面的语句因为参数hash相同所以为真,后面的语句中逻辑或运算符前面的表达式因为本次添加的元素是由String类构造方法创建的对象,与第一次添加的“Tom”地址是不相同的,所以该表达式为false,继续执行逻辑或后面的表达式,key不为null一定是true,逻辑与后面的表达式,key与k进行比较,也就是比较两次添加的字符串是否相同,结果是相同,所以逻辑与为真,逻辑或也为真,外面的逻辑与也为真,所以if判断条件成立,执行if代码块。
第12行:将第一次添加的结点赋值给e。
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;
}
第29行到34行执行的结果和第二个示例中一样,也是返回常量value给put方法,再返回给add方法,add方法再返回false,本次添加失败。
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
4.自定义的类
前几个示例中HashSet集合的泛型都是String,而String类中重写过hashCode方法,所以只要字符串相同打印出来的就是同一串数字;在这个前提下,才保证了add方法的正确实现,那么当HashSet集合的泛型是自定义的类,调用hashCode方法时调用的是Object类中的hashCode方法,而未经重写的Object类中的hashCode方法仅仅是打印对象的地址,只要地址不相同,打印出的数字必定不相同。
就像如下的例子,自定义一个Student类,里面定义一个String类型变量,这时创建两个Student类型对象,调用hashCode方法打印出的数字并不一样:
//自定义Student类
package hashset;
public class Student {
private String id;
public Student(String id) {
this.id=id;
}
}
//测试类
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<Student> set=new HashSet<>();
Student stu1=new Student("110");
Student stu2=new Student("110");
System.out.println(stu1.hashCode());
System.out.println(stu2.hashCode());
}
}
那么问题来了,如果两个Student类对象中的字符串相同,那么往集合中添加的时候能否添加成功呢?
下面代码的运行结果为2,说明第二个对象添加成功了。
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<Student> set=new HashSet<>();
Student stu1=new Student("110");
Student stu2=new Student("110");
set.add(stu1);
set.add(stu2);
System.out.println(set.size());
}
}
我们来分析一下当失去了String类中重写后的hashCode方法的功能以后都有哪里会出现不同的地方。
第一个Student类对象添加的时候和第一个示例的执行过程一样,所以我们直接说第二个对象的添加:
第4行:table中有第一次添加的对象,不为空,且数组的长度为16不为0,所以if代码块不执行。
第6行:因为第一次添加的对象str1和本次添加的对象str2的地址不相同,所以hashCode的返回值便不相同,所以hash()方法的返回值同样也不相同;所以tab[i]和第一次添加的结点并不是同一个,所以tab[i]结点中并没有元素,所以为null,if判断条件成立,执行if代码块。
第7行:创建一个新的结点,将地址赋值给tab[i]。
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;
}
第37到41行的执行情况与第一个示例一样,最终返回null给put方法,然后put方法再返回null给add方法,最后add方法返回true,新元素添加成功。
这样来看的话,当失去了String类中重写后的hashCode方法的功能以后,唯一的影响就是在hash方法中只要对象的地址不相同,返回的数字就不相同,而对象中的String类型变量是否相同对元素是否能添加到HashSet集合中并没有影响。
四.在自定义类中重写方法
在上述的第四个示例中,只能够判断添加到集合中的是否是同一个对象,而不能判断添加进去的对象中的内容是否重复,可是当我们在项目中使用HashSet集合的时候,却需要这一特性来判断添加进去的对象的内容是否重复,所以我们这时就可以根据需求像String类那样对Object类中的方法进行重写。
以第四个示例中的Student类为例:
package hashset;
public class Student {
private String id;
public Student(String id) {
this.id=id;
}
}
①重写hashCode方法
Object类中hashCode的返回值只取决于对象的地址,地址不相同返回值则不相同,而我们现在的需求是如果Student类对象中的字符串变量id相同的话就返回相同的数字,所以我们可以对该方法这样重写:
package hashset;
public class Student {
private String id;
public Student(String id) {
this.id=id;
}
@Override
public int hashCode() {
return this.id.hashCode();
}
}
这样重写过后用Student类对象调用hashCode的返回值就是id调用hashCode的返回值了。这时我们再进行测试,发现结果还是添加进去了。
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<Student> set=new HashSet<>();
Student stu1=new Student("110");
Student stu2=new Student("110");
set.add(stu1);
set.add(stu2);
System.out.println(set.size());
}
那么问题出在哪了呢?我们再来分析一遍第二次添加的时候的putVal方法:
第4行:table中有第一次添加的对象,不为空,且数组的长度为16不为0,所以if代码块不执行。
第6行:由于对hashCode方法进行了重写,只要两个对象中的变量id相同就返回相同的数字,所以i的值与第一次添加时i的值是相同的,也就是说p结点就是第一次添加进元素的那个结点,该结点不为null,所以if的判断条件不成立,执行第8行的else代码块。
第10、11行:p结点也就是第一次添加到的结点,由于hashCode方法已被重写,所以它的hash值与本次添加时的hash值是一样的,即为真;将p结点的key也就是第一次添加的对象,赋值给k,再与key也就是本次添加的对象比较地址,显然地址不相同,所以为假;再看逻辑或后面的表达式,key显然不等于null,但是当key调用equals的时候要注意,由于Student类中并没有对equals方法重写过,所以调用的是Object类中的equals方法,即比较的是对象的地址是否相同,而不同的对象中的id的地址自然不相同,所以该表达式为假,即逻辑或表达式为假,逻辑与表达式也为假,if判断条件不成立,执行第15行else语句。
第16行:进入for循环,对数组中的结点进行遍历。
第17到22行:先判断当前结点的下一个结点是否为空,如果为空的话就将本次添加的结点送进去并结束循环,不为空就继续遍历。
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;
}
第23到26行: 执行到这里说明当前结点不为空,所以对当前结点中的元素进行判断,判断其是否与要添加的元素重复,判断条件与第10、11行代码相同。
第29行:由于HashSet集合的容量是无限大的,所以最终一定会找到一个结点存放新添加的元素,这时e为null,所以if的判断条件一定不成立,不执行if代码块。
第37到41行的执行情况与前面的第一个示例一样,最终返回null给put方法,然后put方法再返回null给add方法,最后add方法返回true,新元素添加成功。
分析完上面的底层代码后发现,需求没有得到解决的原因就是Student类对象调用的equals方法时Object类中的equals方法,所以比较的是第一次添加的对象和本次添加的对象的地址是否一致,所以为了达到目的,我们还需要在Student类中对equals方法进行重写。
②重写equals方法
根据我们的需求,是要当两个不同的对象中的id相同时便添加失败,所以进行如下重写操作:
package hashset;
public class Student {
private String id;
public Student(String id) {
this.id=id;
}
@Override
public int hashCode() {
return this.id.hashCode();
}
@Override
public boolean equals(Object obj) {
Student student = (Student)obj;
return this.id.equals(student.id);
}
}
当Student类对象调用equals方法时,将待比较的Student类对象上转型为Object类,所以在方法中我们首先将该变量下转型回Student类,再调用该对象中的id来比较与待比较的对象的id是否相同,由于id为String类,所以id调用equals方法时调用的是String类重写过的equals方法。
测试结果如下,说明当两个不同对象中的id相同时,第二个对象的添加失败,所以需求达到了。
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<Student> set=new HashSet<>();
Student stu1=new Student("110");
Student stu2=new Student("110");
set.add(stu1);
set.add(stu2);
System.out.println(set.size());
}
}
我们这次只简单分析一下从equals方法相关的那行代码开始:
第10、11行:p结点的hash值与本次的hash值相等所以为真;p结点的对象和本次添加的对象的地址不相同所以为假;本次添加的对象不为null所以为真;最后,key与k进行比较的时候,比较的是两个对象中的id,都是110,所以为真,所以if判断条件为真,执行if代码块。
第12行:将p结点赋值给e。
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;
}
第29行到34行执行的结果和上面的第二个示例中一样,也是返回常量value给put方法,再返回给add方法,add方法再返回false,本次添加失败。
五.bug分析
在该Student类中equals方法的重写上实际上还存在着一个bug,我们新创建一个Dog类,它也有String类型的id,但是只重写了hashCode方法没有重写equals方法。
package hashset;
public class Dog {
private String id;
public Dog(String id) {
this.id = id;
}
@Override
public int hashCode() {
return this.id.hashCode();
}
}
这时我们将HashSet集合的泛型改为Object,然后创建一个Student类型对象,一个Dog类型对象,二者的id是一样的。先将dog添加进去,再添加stu,这时我们测试一下是否能添加进去:
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<Object> set=new HashSet<>();
Student stu=new Student("110");
Dog dog=new Dog("110");
set.add(dog);
set.add(stu);
System.out.println(set.size());
}
}
此时便会报错,原因是我们没有思考到一个问题,我们再来看add方法中的putVal方法:
当添加第二个对象也就是Student类的stu时,第11行中的key调用equals方法,是Student类对象stu在调用重写过的equals方法,与第一个添加的Dog类的dog对象做比较,问题就出在这。
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;
}
这时我们再来分析一下Student类中重写的equals方法:
stu调用该方法时将Dog类型对象dog上转型转为Object类变量,然后在方法中再将该Object类型对象下转型成Student类对象,问题来了,Dog和Student没有任何关系,是不能下转型的,所以编译器便会报错。
package hashset;
public class Student {
private String id;
public Student(String id) {
this.id=id;
}
@Override
public int hashCode() {
return this.id.hashCode();
}
@Override
public boolean equals(Object obj) {
Student student = (Student)obj;
return this.id.equals(student.id);
}
}
此时我们要想修复这个bug,就要让obj中存放的是Student类或是它的子类,这样才能将其下转型为Student类,修改后的代码如下,只有当obj中指向的对象是Student的子类时才能进行下转型:
package hashset;
public class Student {
private String id;
public Student(String id) {
this.id=id;
}
@Override
public int hashCode() {
return this.id.hashCode();
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Student) {
Student student = (Student)obj;
return this.id.equals(student.id);
}else {
return false;
}
}
}