您的位置:首页 > 编程语言 > Java开发

JDK1.7之 HashMap 源码分析

2017-07-19 21:18 239 查看
转载请注明出处:http://blog.csdn.net/crazy1235/article/details/75451812

类继承关系

构造函数

Entry

put
put

putForNullKey

putForCreate

扩容

get

remove

clear

hash

Fail-Fast

小结
参考

JDK1.7 及之前的版本中,HashMap中通过散列链表的形式来存储数据,基于一个数组及多个链表的方式,当hash值冲突的时候,就会在对应的节点以链表的形式存储这些hash值冲突的数据!

整个HashMap的源码实现主要应该关注的有以下几点:

扩容算法

put()

get()

为什么HashMap不是线程安全的?

hash算法

类继承关系

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable


构造函数

先来看几个常量

/**
* 初始容量为16。容量必须是2的指数倍
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;


/**
* 最大容量
*/
static final int MAXIMUM_CAPACITY = 1 << 30;


/**
* 加载因子默认是0.75.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;


平衡因子的作用在于,当存储的容量超过阈值(存储容量和加载因子的乘积)时,要对哈希表进行扩展操作。这个平衡因子的默认数值是JDK约定的。

/**
* 存储键值对对应的Entry数组
*/
transient Entry<K,V>[] table;


/**
* 键值对的个数
*/
transient int size;


/**
* 表示一个阈值,当size超过了threshold就会扩容
*/
int threshold;


/**
* 加载因子
*/
final float loadFactor;


/**
* map结构修改次数,累加
*/
transient int modCount;


/**
* 默认阈值
*/
static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;


public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}


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);

// 找到一个大于等于initialCapacity并且是2的指数的值作为初始容量
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;

this.loadFactor = loadFactor;
// 初始化阈值
threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
// 初始化Entry数组
table = new Entry[capacity];
useAltHashing = sun.misc.VM.isBooted() &&
(capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
init();
}


// 空实现
void init() {
}


// 传进来一个Map存储到HashMap中
public HashMap(Map<? extends K, ? extends V> m) {
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
putAllForCreate(m);
}


private void putAllForCreate(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) // 遍历map
putForCreate(e.getKey(), e.getValue());

// putForCreate() 这里先不说
}


通过上面看到,构造函数的处理无非就是通过传入的初始容量和加载因子(没有则用默认值),然后出事化Entry数组及其他一些变量。

构造函数先分析到这里。

Entry

来看看Entry这是类的内容

// 静态内部类
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next; // 只想下一个entry节点
int hash;

/**
* 构造函数,每次都用新的节点指向链表的头结点。新节点作为链表新的头结点
*/
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;
}

public final boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
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;
}

public final int hashCode() {
return (key==null   ? 0 : key.hashCode()) ^
(value==null ? 0 : value.hashCode());
}

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) {
}
}


从Entry的构造函数可以看出,每次创建新的Entry对象,就会把链表的头结点作为next拼接到新的entry对象上。也就是说每次插入新的map数据时,就会在一个bucket的最前面(链表头部)!

put

put()

/*
* 1. 通过key的hash值确定table下标
* 2. 查找table下标,如果key存在则更新对应的value
* 3. 如果key不存在则调用addEntry()方法
*/
public V put(K key, V value) {
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;
}
}
// 没有在相同hash值的链表中找到key相同的节点
modCount++;
addEntry(hash, key, value, i); // 在i位置对应的链表上添加一个节点
return null;
}


当key为null的时候调用了putForNullKey()函数。

可见HashMap可以put进去key值为null的数据。

从for循环的if判断条件可以看出,如果key值有相同的数据则会覆盖value值,可见HashMap中key值都是唯一的!

putForNullKey()

private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) { // 寻找数组0位置对应的链表key值为null的节点,进而更新value值
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0); // 在数组0位置对应的链表上添加一个节点
return null;
}


下面来看addEentry()

void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) { // 如果数据大小已经超过阈值并且数组对应的bucket不为空,则需要扩容
resize(2 * table.length); // 扩容
hash = (null != key) ? hash(key) : 0; // key为null的时,hash值设为0
bucketIndex = indexFor(hash, table.length); // 确定是哪一个链表(bucket下标)
}

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


//判断k的数据类型选择不同的hash计算方式
final int hash(Object k) {
int h = 0;
if (useAltHashing) {
if (k instanceof String) { // 如果k是Sting类型
return sun.misc.Hashing.stringHash32((String) k);
}
h = hashSeed;
}

h ^= k.hashCode();

// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}


HashMap采用一个Entry数组来存储bucket 。一个bucket就代表一条hash相同的节点链表。

如下图:



接着上面的函数实现来分析。先不看resize()这个扩容算法,先来看createEntry()

void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}


putForCreate()

此方法用在构造函数、克隆或者反序列化的时候调用。不会调整table数组的大小。

private void putForCreate(K key, V value) {
int hash = null == key ? 0 : hash(key);
int i = indexFor(hash, table.length);

/**
* 如果存在key值相同的节点,则更新value值
*/
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
e.value = value;
return;
}
}
// 否则创建新的entry加入某个bucket对应的链表中
createEntry(hash, key, value, i);
}


扩容

现在假设需要扩容,及数据量已经达到了阈值了。

//
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]; // 创建新的数组
boolean oldAltHashing = useAltHashing;
useAltHashing |= sun.misc.VM.isBooted() &&
(newCapacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
boolean rehash = oldAltHashing ^ useAltHashing; // 是否需要重新计算hash值
transfer(newTable, rehash);  // 将table的数据转移到新的table中
table = newTable; // 数组重新赋值
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); //重新计算阈值
}


// 转移数据
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
for (Entry<K,V> e : table) { //遍历旧数组
while(null != e) { //将这一个链表遍历添加到新的数组对应的bucket中
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;
}
}
}


/**
* 得到hash值在table数组中的位置
*/
static int indexFor(int h, int length) {
return h & (length-1);
}


get

/**
* 得到 key = null 对应的value值
*/
private V getForNullKey() {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}


/**
* 根据key得到对应的value值
*/
public V get(Object key) {
if (key == null)
return getForNullKey(); // 如果key为null,则调用getForNullKey()
Entry<K,V> entry = getEntry(key); // 重点在getEntry()函数

return null == entry ? null : entry.getValue();
}


/**
* 根据key得到对应的Entry对象
*/
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key);
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) { // 遍历hash值相同(通过key得到)的那个bucket(链表)
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}


remove

public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key); // !!!
return (e == null ? null : e.value); // 返回key对应的value值
}


final Entry<K,V> removeEntryForKey(Object key) {
int hash = (key == null) ? 0 : hash(key); //计算hash值
int i = indexFor(hash, table.length); // 得到下标
Entry<K,V> prev = table[i];
Entry<K,V> e = prev;

while (e != null) {
Entry<K,V> next = e.next;
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
modCount++; // 操作次数+1
size--;
if (prev == e) // 如果是buckek的头节点是要找的结点,直接将数组指向next
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}

return e; // 如果链表遍历结束还是没找到,则此时e为null,返回null
}


clear

public void clear() {
modCount++; // +1
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0; // 置0
}


hash()

每次put一个键值对或者,通过get得到一个值的时候,都会对key进行hash运算得到hash值

final int hash(Object k) {
int h = 0;
if (useAltHashing) {
if (k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h = hashSeed;
}

h ^= k.hashCode();

// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}


通过上述函数得到hash值之后,在通过 indexFor()函数得到对应table数组的下标!

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


举个例子:



通过二进制的异或,移位,与 等操作,最后运算得到一个下标。

Fail-Fast

下面来关注一下modCount这本变量!

在put() 、remove()、 clear()的时候modCount都会进行+1操作。

对HashMap内容的修改都会增加这个值。

HashMap 通过拉链法实现的散列表,table数组中的每一个Entry又是一个单链表!

看一下HashMap怎么遍历的:

private transient Set<Map.Entry<K,V>> entrySet = null; // 是一个集合


public Set<Map.Entry<K,V>> entrySet() {
return entrySet0();
}


private Set<Map.Entry<K,V>> entrySet0() {
Set<Map.Entry<K,V>> es = entrySet;
return es != null ? es : (entrySet = new EntrySet()); // entrySet为空时new一个EntrySet对象
}


private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public Iterator<Map.Entry<K,V>> iterator() {
return newEntryIterator();  // 创建迭代器
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry)) // 比较类型
return false;
Map.Entry<K,V> e = (Map.Entry<K,V>) o;
Entry<K,V> candidate = getEntry(e.getKey());
return candidate != null && candidate.equals(e);
}
public boolean remove(Object o) {
return removeMapping(o) != null;
}
public int size() {
return size;
}
public void clear() {
HashMap.this.clear();
}
}


其实HashMap内部由三种迭代器

Iterator<K> newKeyIterator()   { // key迭代器
return new KeyIterator();
}
Iterator<V> newValueIterator()   { // value迭代器
return new ValueIterator();
}
Iterator<Map.Entry<K,V>> newEntryIterator()   { // entry迭代器
return new EntryIterator();
}


而这三种迭代器又都继承 HashIterator

private final class ValueIterator extends HashIterator<V> {
public V next() {
return nextEntry().value;
}
}

private final class KeyIterator extends HashIterator<K> {
public K next() {
return nextEntry().getKey();
}
}

private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() {
return nextEntry();
}
}


// hash迭代器
private abstract class HashIterator<E> implements Iterator<E> {
Entry<K,V> next;        // next entry to return
int expectedModCount;   // For fast-fail
int index;              // current slot
Entry<K,V> current;     // current entry

HashIterator() {
expectedModCount = modCount; // 临时存储
if (size > 0) { // advance to first entry
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
}

public final boolean hasNext() {
return next != null;
}

// 每次迭代都会调用次函数得到下一个Entry对象
final Entry<K,V> nextEntry() {
if (modCount != expectedModCount) // 判断
throw new ConcurrentModificationException();
Entry<K,V> e = next;
if (e == null)
throw new NoSuchElementException();

if ((next = e.next) == null) {
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
current = e;
return e;
}

public void remove() {
if (current == null)
throw new IllegalStateException();
if (modCount != expectedModCount) // 判断
throw new ConcurrentModificationException();
Object k = current.key;
current = null;
HashMap.this.removeEntryForKey(k);
expectedModCount = modCount;
}
}


在迭代的过程中,如果发现modCount != expectedModCount,那么就表示有其他的线程对HashMap进行了修改操作,进而就抛出 ConcurrentModificationException 这个异常!

所以:HashMap是非线程安全的!

小结

从上面的分析可以得到以下结论:

HashMap的value可以为null

HashMap是非线程安全的

初始容量和加载因子会影响HashMap的性能

参考

https://www.zhihu.com/question/20733617?wechatShare=1

http://blog.csdn.net/yesuhuangsi/article/details/12241101

http://www.cnblogs.com/todayjust/p/5876533.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: