重写hashCode()方法和equals()方法
1、Object类中有hashCode()和equals方法
public native int hashCode(); //根据地址进行运算得到的伪随机数
public boolean equals(Object obj) {//直接判断内存地址
return (this == obj);
}
A == B: 同一个内存地址。
A.equals(B) :AB对象内容相同,可能是同一个地址,这种情况hashCode一定相同。相反,hashCode相同不一定equals()方法相等。
2、HashSet直接使用了HashMap
public HashSet() {//jdk1.8
map = new HashMap<>();
}
HashMap的put()方法源码分析
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
这一段是扰动函数,通过混合计算hash码的高位和定位来增加随机性。
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)
n = (tab = resize()).length;
//n是HashMap长度,最好为2的次方,减少hash碰撞
if ((p = tab[i = (n - 1) & hash]) == null)
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) // -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;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}