我们再看当存储两个地址不同的对象时第二个如何执行
package sun;
import java.util.HashSet;
public class Test1 {
public static void main(String[] args) {
HashSet<Student> set = new HashSet<Student>();
set.add(new Student("100"));
set.add(new Student("100"));
}
}
package sun;
public class Student {
private String id;
public Student(String id) {
this.id = id;
}
}
在执行该代码时第二个Student对象是二次存入,两次地址是不同的
HashSet add方法代码:
public boolean add(E e){
return map.put(e,PRESENT)==null;;
}
add方法中传入的e为第二个Student对象,PRESENT为HashMap的常量
HashMap put方法:
public V put(K key,V value){
return putVal(hash(key),key,value,false,true);
}
而put方法传入了第二个Student对象的putval方法返回值;在该方法中调用了hash方法
hash方法:
static final int hash(Object key){
int h;
return (key == null)?0:(h = key.hashCode())^(h>>>16);//当传入的key是null时将会返回0;当两个对象的hashCode相同时,他们的hash()返回值也是相同的
}
hashCode()方法:同一对象多次调用该方法结果都相同;当不同对象重写了该方法导致返回值相同,则多次调用该方法结果都相同,由于两次传入的Student对象地址不同,所以他们的hashCode值不同。
HashMap 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);
在调用putval方法时由于当前tab数组在第一次调用时已经建立所以不为null,而且tab数组长度已定义为16;第一个if不执行。
在第二个if判断时, i = (n - 1) & hash 是指数组长度-1 & hash值,即16-1 & hash,因为第一个和第二个值的时候由于hashCode不同,所以存第一个值和存第二个值的时候(n - 1) & hash的值是不同的,所以(p = tab[i = (n - 1) & hash]) == null 的判断结果为true,所以该if成立,所以将第二个Student对象加入集合。