向集合中存储不重复元素代码解析
package sun6;
import java.util.HashSet;
public class Test2 {
public static void main(String[] args) {
HashSet<String> names = new HashSet<String>(); 调用构造方法时,创建HashMap集合对象
names.add("Jim"); 向HashMap的Key存值, HashMap value是一个常量Object
names.add("Luck"); 如何执行
}
}
names调用HashSet中的add方法
public boolean add(E e) { 运行add方法时e为要添加的元素,这里即e第一次为Jim,第二次为Luck。
return map.put(e, PRESENT)==null; PRESENT为常量
}
map调用HashMap中的put方法
public V put(K key, V value) { 这里e将要添加的元素传给key,也就是Luck,常量传给value
return putVal(hash(key), key, value, false, true); 存第一个和第二个值的时候由于hashCode不相同,所以第二次存的对象与第一次存的对象hash(key)结果是不一样的
}
*********************************
在此Key是存储的第二个元素,hash(Key)是一个用hash方法返回的一个数值hashCode
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
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) 由于存第一个对象时table全局变量已经有值了,所以table 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的值是不一样的 ,所以存第二个对象时tab[i = (n - 1) & hash]为null
运行下面一行代码,存储第二个不重复的元素,此时的i与第一个i的值不一样,因为hash值不一样
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)
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) {
V oldValue = e.value; 为常量Object
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}