HashSet理解(一)java集合
HashSet理解(二)怎么做到值不重复
HashSet理解(三)add方法(jdk1.7及以前)是如何插值的
HashSet理解(四)为什么jdk1.7中的头插法会形成环和死循环?
&运算符,具体怎么算的,这篇:java运算符手把手教你计算。按位与有个特点,算式x&y中,当y=2^n-1时,例如3,7,15等,其作用类似于x%y。测试下:
public static void main(String[] args) {
System.out.println(15&15);
System.out.println(16&15);
System.out.println(17&15);
System.out.println(18&15);
System.out.println(19&15);
System.out.println(20&15);
System.out.println(21&15);
System.out.println(22&15);
System.out.println(23&15);
}
运行结果:
static int indexFor(int h, int length) {
return h & (length-1);
}
length初始值是16,length-1就是15。
jdk1.7及以前,插值其实是头插法put方法具体:
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 e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
看看addEntry()方法的四个参数:
- hash是hash(key.hashCode());的返回值,并不是key.hashCode()直接传入。
- key,value都put方法的入参
- i 是hash值对应的数组下标
继续看,这四个参数怎么处理的:
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry e = table[bucketIndex];
table[bucketIndex] = new Entry(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}
e是单链表的头结点,new Entry
static class Entryimplements Map.Entry { final K key; V value; Entry next;//对下一个节点的引用(看到链表的内容,结合定义的Entry数组,是不是想到了哈希表的拉链法实现?!) final int hash;//哈希值 Entry(int h, K k, V v, Entry n) { value = v; next = n; //原头结点放在新头结点的尾部 key = k; hash = h; } ... }
hash值,key,value直接保存在entry里面,然后让next等于原来的头结点。这就是整个完整的头插法。更多详细的源码分析,参考:HashMap源码分析.
为什么没见处理哈希冲突?哈希冲突简单的讲,就是两个key的hash值相同。详细描述参考:数据结构与算法:hash冲突解决。
如何处理hash冲突?
- 拉链法(链地址法)
- 开放定址法
- 再hash法
HashMap处理hash冲突的方式,就是拉链法,即当hash值相同时,直接将entry插入到链表头部。



