//Student类
package sun;
public class Student {
private String id;
public Student(String id) {
this.id = id;
}
}
//Test类
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"));
}
}
//此时set集合中存入了两个对象
//分析add方法的执行过程
1、HashSet中add方法:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
2、HashMap中put方法:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);//存第一个和第二个值的时候由于hashCode不相同,所以第二次存的对象与第一次存的对象hash(key)结果不一样的
}
//hash方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
3、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) //存第一个对象时条件为true 存第二个对象时条件为false
n = (tab = resize()).length; // n=16
if ((p = tab[i = (n - 1) & hash]) == null)// 存第二个对象时因为第一个和第二个值的hashCode不相同,所以存第一个值和存第二个值的时候(n - 1) & hash的值是不一样的 ,所以存第二个对象时tab[i = (n - 1) & hash]为null,条件为true
tab[i] = newNode(hash, key, value, null); //在tab[i]处存入第二个对象
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;
}