hashcode是什么
- java 的hashcode
- hash冲突如何解决
- mysql中的hash索引(后续学习的时候更新)
1、java 的hashcode
产生的由来:想要使用一个对象来查找另一个对象
概念:在java 中的实现和实例,首先在Object中有一个获取hashcode的java native方法hashcode会返回一个int类型的数据
在String中hashCode的实现是将内部的多个字符的值进行相加实现,最后返回多个字符相加的结果
1、在map、set,中,需要重写hashcode和equals来判断是否是同一个对象
//object 中的方法
public native int hashCode();
//String 中的方法
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
//char 类型可以直接转换为int类型所以可以直接相加
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
2、hash冲突
a、什么是hash冲突?示例
由于哈希算法被计算的数据是无限的,而计算后的结果范围有限,因此总会存在不同的数据经过计算后得到的值相同,这就是哈希冲突。
**两个不同的数据计算后的结果一样**
示例:
System.out.println("Aa".hashCode()); // 2112
System.out.println("BB".hashCode()); // 2112
System.out.println("ABCDEa123abc".hashCode()); // 165374702
System.out.println("ABCDFB123abc".hashCode()); // 165374702
//结果
2112
2112
165374702
165374702
解决方案
1. 开放定址算法
2. 链地址法
3. 再哈希发
4. 建立公共溢出区
在java 中解决hash冲突,常用链地址法hashMap中在出现hash冲突的时候会使用链地址法来解决hash冲突
public V put(K key, V value) {
//hash()方法在上面已经出现过了,就不贴了
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;
// tab为空则创建
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 计算index,并对null做处理
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K, V> e;
K k;
// 节点key存在,直接覆盖value
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);
//链表长度大于8转换为红黑树进行处理 TREEIFY_THRESHOLD = 8
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// key已经存在并相等,不往链表加值
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
// key不存在,p,e是老值,p.next是新值
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
//链地址法触发,返回老值,写了这么久代码才知道put返回不仅仅是null。
return oldValue;
}
}
++modCount;
// 超过最大容量 就扩容 threshold:单词解释--阈(yu)值,不念阀(fa)值!顺便学下语文咯。
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
版权声明:本文为mycsdnhmk原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。