不能向集合中存储重复的元素,源代码解析
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("Jim"); 如何执行
}
}
names调用HashSet中的add方法
public boolean add(E e) { 运行add方法时e为要添加的元素,这里即e为Jim
return map.put(e, PRESENT)==null; PRESENT为常量
}
map调用HashMap中的put方法
public V put(K key, V value) { 这里e将要添加的元素传给key,常量传给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) 由于第一个与第二个的hash值一样,但是p = tab[i = (n - 1) & hash]由于第一次存了值,所以不为null,所以该if为false
结论:向HaspMap存储数据时,如果当前数据的hashcode和集合中已存在的元素的hashcode相同,则该if不成立
tab[i] = newNode(hash, key, value, null);
*********************************************************************************
else {
Node<K,V> e; K k;
if (p.hash == hash && 集合中Node元素包含的值的hash,即第一个Jim的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)
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) onlyIfAbsent传递是为false,加!后为true
e.value = value;
afterNodeAccess(e);
return oldValue; 返回老的Jim,没有添加的操作,即添加失败。即放置添加的元素重复
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}