hashcode是什么
- java 的hashcode
- hash冲突如何解决
- mysql中的hash索引(后续学习的时候更新)
1、java 的hashcode
产生的由来:想要使用一个对象来查找另一个对象
概念:在java 中的实现和实例,首先在Object中有一个获取hashcode的java native方法hashcode会返回一个int类型的数据
在String中hashCode的实现是将内部的多个字符的值进行相加实现,最后返回多个字符相加的结果
1、在map、set,中,需要重写hashcode和equals来判断是否是同一个对象
public native int hashCode();
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
2、hash冲突
a、什么是hash冲突?示例
由于哈希算法被计算的数据是无限的,而计算后的结果范围有限,因此总会存在不同的数据经过计算后得到的值相同,这就是哈希冲突。
**两个不同的数据计算后的结果一样**
示例:
System.out.println("Aa".hashCode());
System.out.println("BB".hashCode());
System.out.println("ABCDEa123abc".hashCode());
System.out.println("ABCDFB123abc".hashCode());
2112
2112
165374702
165374702
解决方案
1. 开放定址算法
2. 链地址法
3. 再哈希发
4. 建立公共溢出区
在java 中解决hash冲突,常用链地址法hashMap中在出现hash冲突的时候会使用链地址法来解决hash冲突
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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;
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)
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;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}