HashMap源码基础解读
- 底层原理:
- jdk1.7 :数组+链表
- jdk1.8:数组+链表+红黑树
- 红黑树的根节点、链表的头节点 都是 数组的元素table[i]
- 源码解读
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
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 V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
public static int highestOneBit( int i){
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
return i - (i >>> 1);
}
Integer.highestOneBit((number-1)<<1);
static int indexFor(int h,int length){
return h&(length-1);
}
final int hash(Object k){
int h=hashSeed;
if(0!=h&&k instanceof String){
return sun.misc.Hashing.stringHash32((String)k);
}
h^=k.hashCode();
h^=(h>>>20)^(h>>>12);
return h^(h>>>7)^(h>>>4);
}
HashMap使用技巧
jdk8中的HashMap源码解读
jdk8中的ConcurrentHashMap源码解读