代码:
import java.util.HashSet;
public class Test2 {
public static void main(String[] args) {
HashSet<String> names = new HashSet<String>();
names.add("Jim");//https://上一篇如何存储第一个数据:blog.csdn.net/syhfly2333/article/details/105605240
names.add("Jim");//当输入相同数据怎么执行
}
}
HashSet add
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
HashMap put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);//存第一个和第二个值的时候由于hashCode相同,所以第二次存的对象与第一次存的对象hash(key)结果是一样的,返回的一样
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)值,即i = (16-1 )& hash,因为第一个和第二个值的时候由于hashCode相同,所以存第一个值和存第二个值的时候(n - 1) & hash的值是一样的,因为第一次已经在此(n - 1) & hash 位置存了数据tab[i = (n - 1) & hash]不为null为Jim, p不为null (p = tab[i = (n - 1) & hash]) == null 结果为 false
// 可得结论:向HaspMap存储数据时,如果当前数据的hashcode和集合中已存在的元素的hashcode相同,则该if不成立,即存储相同的数据,该if是不执行的,由else执行相同数据
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,判断俩次存储的key是否地址一样,==是比较地址的。由于两次的对象是同一个地址 ,结果为true;如果代码是names.add(new String("Jim"));又创建了新的对象,地址不同,则false;
//(key != null && key.equals(k)) 是判断俩次输入数据的内容是否一样,这里调用的是String重写的equals方法,结果为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的oldValue,存储失败:return putVal(hash(key), key, value, false, true); return map.put(e, PRESENT)==null;不成立,为false,失败
}
}
++modCount;
if (++size > threshold)