详述HashSet类add方法(二)
接上一篇文章,第二次向HashSet中添加第二个值(与第一个值相同)的添加步骤
public class Test2 {
public static void main(String[] args) {
HashSet<String> names = new HashSet<String>();
names.add("Jim");
names.add("Jim");//如何执行
}
}
1.调用add()方法
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
2调用map.put()方法
存第一个和第二个值的时候由于hashCode相同,所以第二次存的对象与第一次存的对象hash(key)结果是一样的
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
3调用putVal()方法
走第一个if,因为Tab里有值且长度不为0,返回false,n为16
走第二个if,因为第一个值与第二个值相同,所以计算的i值一样,第二次存的时候发现此地址有值,if判断为false,走else部分
走else的第一个if,因为p.hash == hash为真,(k=p.key)==key为真,所以if为真,将第一个值的地址赋值给e
接着走else的第二个if,e不为null,返回旧值,存储失败
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全局变量已经有值了,所以tabl tab不为空 tab.length不等于0,所以 该if为false n为 16
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)// i = (n - 1) & hash 数组长度-1 & hash值,即16-1 & hash,因为第一个和第二个值的时候由于hashCode相同,所以存第一个值和存第二个值的时候(n - 1) & hash的值是一样的,因为第一次已经在此(n - 1) & hash 位置存了数据tab[i = (n - 1) & hash]不为null p不为null (p = tab[i = (n - 1) & hash]) == null false 结论:向HaspMap存储数据时,如果当前数据的hashcode和集合中已存在的元素的hashcode相同,则该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))))// (k = p.key) == key,由于两次的对象时一个地址 true,names.add(new String("Jim")); 则false;(key != null && key.equals(k)) 为true
e = p;//将第一个Jim的地址为e
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;// e.value 常量Object
if (!onlyIfAbsent || oldValue == null)// onlyIfAbsent本来就为false,所以!onlyIfAbsent true
e.value = value;
afterNodeAccess(e);
return oldValue;//返回第一个Jim,存储失败
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);