一、HashSet中对象的创建
在分析HashSet的add方法的底层代码之前我们先要理解HashSet集合中的对象是如何创建的。
先创建一个JavaWeb工程,引入hashset的包,创建含有HashSet类的方法,然后就可以进入HashSet的底层代码:
package hashset;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<String>name=new HashSet<>();
}
}
然后点击进入HashSet的底层代码,其实质是创建了一个HashMap类集合的对象,将它的值赋给了全局变量map:
public HashSet(){
map=new HashMap<>();
}
二、详述add方法中其他方法
首先来叙述HashSet中add方法的调用,下面是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方法的返回值为null,使用了map全局变量(该块内存中存储的是HashMap类集合中的对象)调用HashMap类中的put方法,再次点击put方法,分析put方法的底层代码:
public boolean add(E e){
return map.put(e,PRESENT)==null;
}
下面是put方法的底层代码,put方法中调用了putVal方法,这个方法的第一个参数传递为key的hash方法,下面将会分析hash方法:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
1、(Object key)中的hash方法
这个方法返回值由三位运算符运算出来,当传入的参数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修饰符修饰的没有方法体的方法,说明这个方法是Java语言native方法调用底层的C语言实现的(就像当下流行的Pathon语言是既可以调用Java语言又可以调用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());
}
}
上述运行结果可以看出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方法,得到如下的底层代码:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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;
}
这个底层代码中还存在resize方法,是我们要分析的第二个方法从而得知putVal方法是怎样运行的。
2、resize()方法
进入resize方法的底层代码,我们目的是分析add方法,所以只需知道resize方法在其中起一个什么即可
import java.util.HashMap.Node;
import java.util.HashMap.TreeNode;
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;
}
下面分析resize方法中重点代码行:
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab;//第一行代码新创建了一个Node<k,v>类型的数组newTab,第二行将该数组newTab赋值给了全局变量table,所以说执行完该resize方法后,全局变量table中存放的就是一个Node<k,v>类型的数组了。
return newTab;//这行代码中方法的返回值为newTab,正是新创建的Node<k,v>类型的数组,也就是说执行完resize方法之后全局变量table和该方法的返回值是同一个Node<k,v>类型数组的同一个地址值。
还有一点要注意到,那就是该数组的长度,在Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];中创建时显示长度为newCap,这时我们来看 newCap = DEFAULT_INITIAL_CAPACITY;newCap被赋值为一个名为DEFAULT_INITIAL_CAPACITY的常量,按住Ctrl键点击该常量,查看到下面这行代码,所以该常量的值为16,也就是说resize方法返回的和全局变量table中的同一个数组的长度为16。
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
三、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方法,传入。两个参数,一个是要添加的字符串,另外一个是常量。
public boolean add(E e){
return map.put(e,PRESENT)==null;
}
接下来put方法调用putVal方法,传入后面括号中的五个参数,第一个是调用hash方法动态运算式算出来的一个数值,第二个是我们想要添加的指定字符串,第三个为上述常量,第四和第五都是对应下面参数的boolean型返回值。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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;
}
下面是对putVal方法实例分析:
if ((tab = table) == null || (n = tab.length) == 0)//先将全局变量table赋值给局部变量tab,但是由于是第一次往集合中添加元素,所以table变量中还是最开始的默认值null,所以该表达式的值为null,也就是说(tab = table) == null表达式的值为true,由于后面是逻辑或运算符,所以后面的表达式不需要看,该if判断条件为真,执行if代码块。
n = (tab = resize()).length;//首先调用resize方法为tab赋值,刚才分析过resize方法的返回值为Node<k,v>类型数组,且在方法中为全局变量table赋值同一个数组,所以该表达式执行过后table和tab中存放的是同一个Node<k,v>类型数组的地址值;然后再取该数组的长度将其赋值给n,刚才分析resize方法时分析过该数组的长度为16,所以n的值被赋值为16。
if ((p = tab[i = (n - 1) & hash]) == null)//首先将n-1也就是15与第一个参数hash进行按位与运算符,因为第一个参数hash是由hash(key)方法动态算出来的一个数,所以将其与15按位与运算之后得到的还是一个动态的数,再把这个数赋值给i后,将tab数组中的第i个结点赋值给p,因为这是第一次添加元素,所以数组中所有结点均为空,所以该if判断条件(p = tab[i = (n - 1) & hash]) == null成立,执行if代码块。
tab[i] = newNode(hash, key, value, null);//i是我们刚才算术式子的值所赋给的变量,调用newNode方法创建一个新的结点赋值给tab数组的第i个结点。
return null;返回值为null返回上一级的put方法中。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
然后put方法返回null到上一级的add方法中,得出这个表达式的值为true,所以add方法的返回值为true,证明我们想要添加的第一个字符串添加成功。
public boolean add(E e){
return map.put(e,PRESENT)==null;
}
2、传入第二个字符串内容相同的字符串举例:
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方法的分析
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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)//先将全局变量table赋值给局部变量tab,由于table是全局变量,所以里面存储的还是上一次添加元素时的那个数组的地址,数组里存储着上一次添加进去的那个元素“Tom”,所以此时不为null,该表达式(tab = table) == null为false,再看逻辑或运算符后面的表达式,将tab数组的长度赋值给n,因为tab数组里存的是刚才table给赋的值,所以数组长度依然为16,不为0,所以表达式为false,if的判断条件不成立,执行第下面的第二行。
if ((p = tab[i = (n - 1) & hash]) == null)//将n-1也就是15与参数hash进行按位与运算,因为刚才分析过String类中只要字符串相同,hashCode方法打印的数字便相同,而hash()方法中计算公式正是调用hashCode方法计算出来的,所以只要传入hash()方法的字符串相同,得到的数就是相同的,又因为hash参数是由hash(key)计算出来的,而这两次传入的key均为“Tom”,所以本次添加时的hash值和第一次添加时的hash值是一样的,所以计算出来的i值和第一次添加时的i值也是一样的,也就是说tab数组的第i个结点就是第一次添加元素的那个结点,因为里面已经有第一次添加的元素了,所以当然不为null,所以if判断条件不成立,执行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.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))//首先这是一个逻辑与运算符,先看运算符前面的表达式,在if ((p = tab[i = (n - 1) & hash]) == null)中已经把第一次添加的结点的地址赋值给了p,所以p.hash就是该结点的hash,而本次添加元素时计算出来的hash已经分析了和上次是一样的,所以逻辑与运算符前面的表达式为true;再看逻辑与运算符后面的是一个逻辑或表达式,逻辑或前面的表达式是将p结点的key值赋值给k,也就是第一次添加的“Tom”,而==后面的key是本次添加的“Tom”,等号运算符比较的是二者的地址,又因为二者都是直接赋值创建的对象,所以都是存储在堆中的常量池中,地址也是相同的,所以该表达式为真,逻辑或表达式也为真,前面的逻辑与表达式也为真,所以该if判断条件成立,执行if代码块。
e = p;//p是第一次添加的结点,将该结点地址赋值给e。
if (e != null) { // existing mapping for key//因为e中存储的是第一次添加的结点,不为null,所以if判断条件成立,执行if代码块。
if (!onlyIfAbsent || oldValue == null)//onlyIfAbsent是该方法传入的第四个参数,由put方法传入的是一个false,所以逻辑非之后是一个true,由于该表达式是逻辑或,所以直接得出if判断条件成立,执行if代码块。
e.value = value;//将第一次添加的结点中的value值覆盖为本次添加value,当然这在HashSet中无影响,因为value始终都是一个常量。
return oldValue;//返回oldValue值,也就是第一次添加时的value常量,到上一级的put方法中,putVal方法结束。
put方法再将value常量返回给上一级的add方法,因为此时put的返回值不是null,所以add方法返回false,所以第二个字符串添加失败。
3、两种创建String类对象的方式
上面的方法是直接赋值创建的对象,所以地址也是相同的,下面是两种不同的创建方式,这个时候会不会添加成功呢?
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方法的分析
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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)//和第二个示例的执行情况一样,不执行if代码块。执行下面的if语句
if ((p = tab[i = (n - 1) & hash]) == null)//由于只要String类的字符串相同,参数hash的值便相同,所以执行情况和第二个示例也一样,执行 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.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))//逻辑与运算符前面的语句因为参数hash相同所以为真,后面的语句中逻辑或运算符前面的表达式因为本次添加的元素是由String类构造方法创建的对象,与第一次添加的“Tom”地址是不相同的,所以该表达式为false,继续执行逻辑或后面的表达式,key不为null一定是true,逻辑与后面的表达式,key与k进行比较,也就是比较两次添加的字符串是否相同,结果是相同,所以逻辑与为真,逻辑或也为真,外面的逻辑与也为真,所以if判断条件成立,执行if代码块。
e = p;//将第一次添加的结点赋值给e。
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
//执行的结果和第二个示例中一样,也是返回常量value给put方法,再返回给add方法,add方法再返回false,本次添加失败。
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类对象中字符串的内容相同,那么向集合中添加(使用add方法)能否成功呢?
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());
}
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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;
}
我们来分析一下自定义类中重写后的hashCode方法的功能以后都有哪里会出现不同的地方。
第一个Student类对象添加的时候和第一个示例的执行过程一样,所以我们直接说第二个对象的添加:
if ((tab = table) == null || (n = tab.length) == 0)//table中有第一次添加的对象,不为空,且数组的长度为16不为0,所以if代码块不执行。
if ((p = tab[i = (n - 1) & hash]) == null)//因为第一次添加的对象str1和本次添加的对象str2的地址不相同,所以hashCode的返回值便不相同,所以hash()方法的返回值同样也不相同;所以tab[i]和第一次添加的结点并不是同一个,所以tab[i]结点中并没有元素,所以为null,if判断条件成立,执行if代码块。
tab[i] = newNode(hash, key, value, null);//创建一个新的结点,将地址赋值给tab[i]。
最终返回null给put方法,put方法将null返回给add方法,最后add方法将会返回true,此时新的元素添加成功。
这样来看的话,当失去了String类中重写后的hashCode方法的功能以后,唯一的影响就是在hash方法中只要对象的地址不相同,返回的数字就不相同,而对象中的String类型变量是否相同对元素是否能添加到HashSet集合中并没有影响,只是内容是否相同对hash产生影响。
四.在自定义类中重写方法
在上述的第四个示例中,只能够判断添加到集合中的是否是同一个对象,而不能判断添加进去的对象中的内容是否重复,可是当我们在项目中使用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方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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)//table中有第一次添加的对象,不为空,且数组的长度为16不为0,所以if代码块不执行。
if ((p = tab[i = (n - 1) & hash]) == null)//由于对hashCode方法进行了重写,只要两个对象中的变量id相同就返回相同的数字,所以i的值与第一次添加时i的值是相同的,也就是说p结点就是第一次添加进元素的那个结点,该结点不为null,所以if的判断条件不成立,执行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.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))//p结点也就是第一次添加到的结点,由于hashCode方法已被重写,所以它的hash值与本次添加时的hash值是一样的,即为真;将p结点的key也就是第一次添加的对象,赋值给k,再与key也就是本次添加的对象比较地址,显然地址不相同,所以为假;再看逻辑或后面的表达式,key显然不等于null,但是当key调用equals的时候要注意,由于Student类中并没有对equals方法重写过,所以调用的是Object类中的equals方法,即比较的是对象的地址是否相同,而不同的对象中的id的地址自然不相同,所以该表达式为假,即逻辑或表达式为假,逻辑与表达式也为假,if判断条件不成立,执行 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;
}
}/
for (int binCount = 0; ; ++binCount) {//进入for循环,对数组中的结点进行遍历。
if ((e = p.next) == null) {//先判断当前结点的下一个结点是否为空,如果为空的话就将本次添加的结点送进去并结束循环,不为空就继续遍历。
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;//执行到这里说明当前结点不为空,所以对当前结点中的元素进行判断,判断其是否与要添加的元素重复,判断条件与if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))相同。
if (e != null) { // existing mapping for key//由于HashSet集合的容量是无限大的,所以最终一定会找到一个结点存放新添加的元素,这时e为null,所以if的判断条件一定不成立,不执行if代码块。
后面返回语句的执行情况与前面的第一个示例一样,最终返回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());
}
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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 (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))//p结点的hash值与本次的hash值相等所以为真;p结点的对象和本次添加的对象的地址不相同所以为假;本次添加的对象不为null所以为真;最后,key与k进行比较的时候,比较的是两个对象中的id,都是110,所以为真,所以if判断条件为真,执行if代码块。
e=p;//将p结点赋值给e。
后面返回值代码块执行的结果和上面的第二个示例中一样,也是返回常量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时,if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))中的key调用equals方法,是Student类对象stu在调用重写过的equals方法,与第一个添加的Dog类的dog对象做比较,问题就出在这。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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;
}
}
}