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

java容器源码分析(四)——HashMap

2015-12-17 00:00 567 查看
摘要: 详细分析HashMap的实现。

本文内容:

Hash

HashMap概述

HashMap源码分析

Hash表

数据结构中都学过Hash,我们要说的HashMap采用拉链法(数组+链表)实现。数组具有根据下标快速查找的特点,链表动态增加删除元素。



(来源:http://www.cnblogs.com/hzmark/archive/2012/12/24/HashMap.html)

看上图,对于HashMap的内部结构应该是一目了然了。

HashMap概述

HashMap是一个Key-Value容器,应该是使用得最多的map了吧。看继承关系图



HashMap继承了AbstractMap、Map,实现了Cloneable和Serializable

HashMap源码分析

看一下HashMap的一些属性

/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/**
* An empty table instance to share when the table is not inflated.
*/
static final Entry<?,?>[] EMPTY_TABLE = {};

/**
* The table, resized as necessary. Length MUST Always be a power of two.
*/
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

/**
* The number of key-value mappings contained in this map.
*/
transient int size;

/**
* The next size value at which to resize (capacity * load factor).
* @serial
*/
// If table == EMPTY_TABLE then this is the initial capacity at which the
// table will be created when inflated.
int threshold;

/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;

/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash).  This field is used to make iterators on Collection-views of
* the HashMap fail-fast.  (See ConcurrentModificationException).
*/
transient int modCount;

/**
* The default threshold of map capacity above which alternative hashing is
* used for String keys. Alternative hashing reduces the incidence of
* collisions due to weak hash code calculation for String keys.
* <p/>
* This value may be overridden by defining the system property
* {@code jdk.map.althashing.threshold}. A property value of {@code 1}
* forces alternative hashing to be used at all times whereas
* {@code -1} value ensures that alternative hashing is never used.
*/
static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;


其中,实际的元素就存放在table数组里面。

接着继续看构造函数

public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, 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;
threshold = initialCapacity;
init();
}


平常我们都直接调用默认构造函数,默认构造函数调用了HashMap(int initialCapacity,float loadFactor)方法。其中DEFAULT_INITIAL_CAPACITY=16,DEFAULT_LOAD_FACTOR=0.75。我们看HashMap(int initialCapacity,float loadFactor)主要是给this.loadFactor和threshold赋值,然后调用init()方法,init()方法在HashMap中是空方法。

构造这一步完成的工作是给loadFactor和threshold赋值!

前面说到HashMap的元素存放在table数组。

transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;


这是个Entry类型的,是HashMap的内部静态类,其实现了Map.Entry接口。

Map.Entry接口定义如下:

interface Entry<K,V> {
K getKey();

V getValue();

V setValue(V value);

boolean equals(Object o);

int hashCode();
}


HashMap中Entry实现:

static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash;

/**
* Creates new entry.
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}

//省略
}


可以看出,Entry有key,value,next,hash这几个属性。

put(K key,V value)方法:

public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
//遍历相同hash的元素
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;
}


如果table为空,则调用inflateTable方法扩容。然后,添加元素分两种情况:key为null,key不为null。

先看一下扩容方法inflateTable(int toSize):

private void inflateTable(int toSize) {
// Find a power of 2 >= toSize
int capacity = roundUpToPowerOf2(toSize);

threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}


table大小是capacity.后面还调用了initHashSeedAsNeeded方法,它有什么用呢?

/**
* Initialize the hashing mask value. We defer initialization until we
* really need it.
*/
final boolean initHashSeedAsNeeded(int capacity) {
boolean currentAltHashing = hashSeed != 0;
boolean useAltHashing = sun.misc.VM.isBooted() &&
(capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
boolean switching = currentAltHashing ^ useAltHashing;
if (switching) {
hashSeed = useAltHashing
? sun.misc.Hashing.randomHashSeed(this)
: 0;
}
return switching;
}


这个,这里没看懂要做什么!先放一下!

继续看put方法,当key不为null时,调用hash方法产生一个hash值:

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

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


Retrieve object hash code and applies a supplemental hash function to the result hash, which defends against poor quality hash functions. This is critical because HashMap uses power-of-two length hash tables, that otherwise encounter collisions for hashCodes that do not differ in lower bits. Note: Null keys always map to hash 0, thus index 0.

大意是说这个算法是减少碰撞(collisions)的,原理求大神告知!!

/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}


indexFor获取元素应该存放在那个buket。length-1的原因是为了避免超出table数据的上界。

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


addEntry先判断要不要扩容。扩容是扩大一倍。然后调用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++;
}


可看出,这是在表头插入节点。

看下resize 方法,它是如何扩大容器的呢?

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


先定义了一个新数组,然后调用transfer将旧元素赋值到新的table上。

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


这里, rehash作为一个开关,来控制是否需要重新hash,initHashSeedAsNeeded的作用可以看到了。是作为判断扩容时是否需要rehash的。从transfer方法中也可以看到为什么HashMap中会有这句说明:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

HashMap不保证元素的位置,也不保证元素原先的位置不变。

put的方法差不多 了,看下当key为null时,是如何的

/**
* Offloaded version of put for null keys
*/
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}


由addEntry看到,key为null时,是存放在table的0下标里面的。

get(Object key)方法:

public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);

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


get也分为两种情况,key为null及key不为null。

先看一下key为null的情况:

private V getForNullKey() {
if (size == 0) {
return null;
}
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}


key为null在table[0],然后直接链表遍历就可以了。

当null不为null时,通过getEntry获取元素:

final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}

int hash = (key == null) ? 0 : hash(key);
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}


先根据hash找出元素在哪个槽,然后遍历出该元素。

看下containsKey(Object key):

public boolean containsKey(Object key) {
return getEntry(key) != null;
}


containsKey(Object key)方法很简单,只是判断getEntry(key)的结果是否为null,是则返回false,否返回true。

(内容太长,oschina不能保存,待续)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 容器 源码分析