java 中HashMap解决hash冲突问题
来源:互联网 发布:淘宝 钛合金螺丝 真假 编辑:程序博客网 时间:2024/06/01 09:32
摘至 jdk1.6 HashMap的源代码:
public V put(K key, V value) {
if (key == null)return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) { // 查找hash位置上的值
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { // 如果找到key相同的值,则更小value,说明之前存储了key
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
// 执行到这步,说明以前没有存储key值,下面需要存在这个新的key值
modCount++; // HashMap 不是线程安全,当hashnext时会判断modCount的值是否变化了,变化了说明查询的时候,有另外的线程更新了HashMap
addEntry(hash, key, value, i); // 存储新的key值
return null;
}
// 在这个方法里面解决了hashcode冲突的问题,Entry 是一个链表,没有冲突那么Entry只有一个记录,如果有冲突Entry中会有多个记录
// 查找到记录时,还是比较key值是否相同
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex]; // 没有冲突 则 e为空,有冲突则把原来的对象放在e的next地址上。
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
public V get(Object key) {
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) // 查找时,通过hash得到Entry后,还需要比较Entry的key值是否相同,相同则找到了所要的记录。
return e.value;
}
return null;
}
- java 中HashMap解决hash冲突问题
- 【Java-集合】HashMap-Hash冲突解决
- Java 8中HashMap冲突解决
- Java 8中HashMap冲突解决
- Java 8中HashMap冲突解决
- HashMap解决hash冲突的方法
- 链表法HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决Hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- HashMap解决hash冲突的方法
- Spring quartz定时器动态多任务实现
- 黑马程序员 高新技术——JAVA1.5新特性及反射
- chapter13 机器学习之利用PCA简化数据
- Android 的Activity和Service之间的通信
- bootstrap使用鼠标右键菜单
- java 中HashMap解决hash冲突问题
- mysql妙用bit存储信息
- MCMC(Markov Chain Monte Carlo) and Gibbs Sampling
- Object+C语法快速入门
- bugzilla 导出csv乱码
- chapter14 机器学习之利用SVD简化数据
- 将webkit内核封装为duilib的浏览器控件
- 【转载】JQUERY标签选择器详细说明
- android中listView下拉刷新