import java.util.HashSet;
public class Test2 {
public static void main(String[] args) {
HashSet<String> names = new HashSet<String>();
names.add("Jim");
names.add("Jim");//如何执行
}
}
1、HashSet中add方法:
public boolean add(E e) { return map.put(e, PRESENT)==null; }//向HashMap集合的map对象中的key存值 |
2、HashMap中put方法:
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); } |
3、HashMap中hash方法:
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }//存第一个和第二个值的时候由于hashCode相同,所以第二次存的对象与第一次存的对象hash(key)结果是一样的
|
4、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全局变量已经有值了,所以tab=table不为空,所以此条件语句执行 //到(tab = table) == null便不会执行下去,n还是为16 n = (tab = resize()).length; if ((p = tab[i = (n - 1) & hash]) == null)//因为第一个和第二个值对应的n和hash值相同,所以存第一个值和存第二个值的时候(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)))) //1、 p.hash指集合中Node元素包含的值的hash,即第一个Jim的hash值;p.key指集合中Node元素包含的key,即第一个Jim的hash值;所以 //p.hash == hash为true //2、==在引用数据类型中比较地址是否相同,(k = p.key)与key地址相同,true;若改为names.add(new String("Jim")), 则false; //3、(key != null && key.equals(k)) 为true,其中equals比较内容是否相同,所以该条件语句执行 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 //执行完上面的if语句后执行该语句 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); return null; } |