您的位置:首页 > 其它

HashMap源码阅读

2017-04-20 11:16 274 查看
题外话:

HashMap线程不安全,Hashtable线程安全。

Hashtable的线程安全性体现在一些put get方法都用synchronized关键字修饰。

ConcurrentHashMap的源码实现采用了不同的加锁机制,称为分段锁。

最近读了hdfs的部分源码和设计思想,先说几句源码阅读心得,先理解设计思想,再进行源码阅读,所有的数据结构和算法都是需求驱动。

1 HashMap设计思想

我们在使用HashMap时,都知道这是key-value的存储形式,那么怎么做到key不重样,又能根据key很快的找到对应的value值呢,怎么才能做到很快的插入一个元素呢?这些需求驱动了HashMap的设计,HashMap的源码实际上是实现了哈希表这种数据结构,我们在数据结构课中学过,数组和链表是两种基本的数据结构,数组的特点是空间连续(大小固定)、寻址迅速,但是插入和删除时需要移动元素,所以查询快,增加删除慢。而链表恰好相反,可动态增加或减少空间以适应新增和删除元素,但查找时只能顺着一个个节点查找,所以增加删除快,查找慢,而哈希表是结合了两者的优点形成的一种数据结构,如下图所示:



现在来回答上面问题,怎么判断key的相同与不同,通过Object的方法hashcode和equals来保证,比如String的hashcode和equals方法,见String源码阅读,怎么保证快速查找和插入,先散列key的hashcode值,找到对应的桶,缩小范围,采用链表结构快速插入元素。

2 属性值,可以发现在jdk源码中,很喜欢用位运算,左移<<,右移>>,异或^。动态增长容量策略:先设置默认值,不满足时再扩充容量。

size是实际key-value键值对个数,这个值是加入一个元素增加一个

CAPACITY是能存储多少个键值对,这个值是动态增加

// 默认初始容量,必须是2的幂
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
* 最大容量,必须是2的幂且小于2的30次方,传入容量过大将被这个值替换
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
//装载因子,默认0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;

static final Entry<?,?>[] EMPTY_TABLE = {};

/**
* 存储数据的Entry数组,长度是2的幂
*/
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

/**
* map中实际的key-value的键值对个数
*/
transient int size;
//需要调整大小的极限值(容量*装载因子)
int threshold;
// 装载因子
final float loadFactor;
// map被修改次数
transient int modCount;


3 HashMap的构造方法

//初始容量值小于0,抛异常,大于最大值,就强制改成最大值,MAXIMUM_CAPACITY
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;
threshold = initialCapacity;
init();
}

/**
* Constructs an empty <tt>HashMap</tt> with the specified initial
* capacity and the default load factor (0.75).
*
* @param  initialCapacity the initial capacity.
* @throws IllegalArgumentException if the initial capacity is negative.
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}


到这里有个疑问,table是什么时候初始化的?长度是多少,怎么增长,增长策略是什么?

4 HashMap.Entry类的具体实现

Entry

static class Entry<K,V> implements Map.Entry<K,V> {
final K key;//key值
V value;//value值
Entry<K,V> next;//下一个Entry对象
int hash;//hash值

// 构造方法,在链式结构中,可以用指定下个Entry的方法将链表连成一个大链表
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}

public final K getKey() {
return key;
}

public final V getValue() {
return value;
}

public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
//重写equals方法
public final boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
// Key相等且Value相等则两个Entry相等
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}
//key的hashcode和value的hashcode做异或运算
public final int hashCode() {
return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
}
//重写toString方法,使输出更清晰
public final String toString() {
return getKey() + "=" + getValue();
}

/**
* This method is invoked whenever the value in an entry is
* overwritten by an invocation of put(k,v) for a key k that's already
* in the HashMap.
*/
void recordAccess(HashMap<K,V> m) {
}

/**
* This method is invoked whenever the entry is
* removed from the table.
*/
void recordRemoval(HashMap<K,V> m) {
}
}


5 put方法,直到put方法,才看到了用来存储数据的table的初始化工作

public V put(K key, V value) {
if (table == EMPTY_TABLE) {
//在这里初始化一个table用来存储数据
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> 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;
}
/**
* Inflates the table.
*/
private void inflateTable(int toSize) {
// 找到一个size,是2的幂,且要大于toSize
int capacity = roundUpToPowerOf2(toSize);

threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
//在bucketIndex处添加新的Entry
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}

createEntry(hash, key, value, bucketIndex);
}


PS:threshold 的作用到底是什么 在源码中可以得到,threshold 的下一个值等于capacity * load factor. 即容量是16时,load factor是0.75,threshold 的值是12。为什么这个值不等于capacity呢?

例如initially default capacity = 16 , load factor = 0.75 那么threshold = (capacity * load factor) = (16 * 0.75) = 12. 当添加第13个元素时 HashMap 会resize,为什么要维持一个这样的值? 这是查找时间和空间的tradeoff,这个问题等价于load factor的存在意义,可参见 “The Art of Computer Programming” vol 3. 因为当一个map很满时,散列和开放式寻址就会停止工作。

参考:https://stackoverflow.com/questions/27384261/in-hashmap-why-threshold-value-the-next-size-value-at-which-to-resize-is-capac

为什么要有load factor,意义在哪?

https://stackoverflow.com/questions/10901752/what-is-the-significance-of-load-factor-in-hashmap

如果确定数据的位置

int hash = hash(k.hashCode());
int i = indexFor(hash, table.length);


第一行,是得到哈希值,第二行,则是根据哈希指计算元素在数组中的位置了,位置的计算是将哈希值和数组长度按位与运算。

static int indexFor(int h, int length) {
return h & (length-1);
}


“h & (length-1)”其实这里是很有讲究的,为什么是和(length-1)进行按位与运算呢?这样做是为了提高HashMap的效率。什么?这样能提高效率?且听我细细道来。

首先我们要确定一下,HashMap的数组长度永远都是偶数,即使你在初始化的时候是这样的new HashMap(15,0.75);因为在构造函数内部,上面也讲过,有这样的一段代码

while (capacity < initialCapacity)
capacity <<= 1;


所以length-1一定是个奇数,假设现在长度为16,减去1后就是15,对应的二进制是:1111。

假设有两个元素,一个哈希值是8,二进制是1000,一个哈希值是9,二进制是1001。和1111与运算后,分别还是1000和1001,它们被分配在了数组的不同位置,这样,哈希的分布非常均匀。

那么,如果数组长度是奇数,减去1后就是偶数了,偶数对应的二进制最低位一定是0了,例如14二进制1110。对上面两个数子分别与运算,得到1000和1000。看到了吗?都是一样的值,哈希值8和9的元素多被存储在数组同一个位置的链表中。在操作的时候,链表中的元素越多,效率越低,因为要不停的对链表循环比较。所以,一定要哈希均匀分布,尽量减少哈希冲突,减少了哈希冲突,就减少了链表循环,就提高了效率。

HashMap的扩容

元素个数超过阈值,那么hashentry大小成为原来的两倍,并新建一个hashentry保存所有的元素,其中每个元素的hash值不重新计算,index会重新计算。见如下代码:

void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}

Entry[] newTable = new Entry[newCapacity];
transfer(newTable, initHashSeedAsNeeded(newCapacity));
table = newTable;
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
/**
* Transfers all entries from current table to newTable.
*/
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  源码 hashmap 设计