此时我们来分析当添加重复元素进HashSet集合时的情况
源码如下:
add方法:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
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);
}
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的值是一样的,因为第一次已经在此(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//集合中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) // -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);
return null;
}
当我们像集合中添加元素时候,首先会判断集合中是否存在重复元素,如果存在重复元素,那么会返回第一个Jim到add方法,此时显然不为空,那么
return map.put(e, PRESENT)==null;
此时显然为false,存储失败
需要我们注意的是,hash()方法主要用来判断元素内容是否相等
演示如下:
String str1 = "111";
String str2 = new String("111");
System.out.println(hash(str1));//48657
System.out.println(hash(str2));//48657
Student stu1 = new Student();
Student stu2 = new Student();
System.out.println(hash(stu1));//1
System.out.println(hash(stu2));//1 (重写了Student类中的hash方法,返回值为1)