1.Hash算法
散列表,又叫哈希表,它是基于快速存取的角度设计的,也是一种典型的空间换时间的做法。
散列表是根据关键码值而直接进行访问的数据结构。
哈希冲突:即两个元素通过散列函数得到的地址相同。
2.源码分析
·构造方法
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
○ int类型构造方法
//可以自定义负载因子
public HashMap(int initialCapacity, float loadFactor) {
//判断初始容量
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//判断容量最大值
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//负载因子判断
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
//tableSizeFor
this.threshold = tableSizeFor(initialCapacity);
}
//计算初始容量,结果为比cap大的最小的2的指数幂
//cap=12-->结果为2^4=16
static final int tableSizeFor(int cap) {
int n = cap - 1;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
○ 参数为 Map<? extends K, ? extends V> m 的构造方法
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
//传入集合大小
int s = m.size();
if (s > 0) {
//判断Node<K,V>[] table数组是否为null
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
//扩容
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
//计算hash值,放入map
putVal(hash(key), key, value, false, evict);
}
}
}
//获取key的hash值
static final int hash(Object key) {
int h;
//对象的hashcode值 ^(异或) 对象的hashcode值的高位(前16位)
//目的:尽可能降低hash冲突,提高hashcode的随机性
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
例如:
hashcode = 1101 1001 , 容量 = 15
1101 1001
^0000 1101
-----------
1101 0100
& 0000 1111
-----------
0000 0100