1.概述
HashMap是一个实现了Map接口的哈希表的实现,HashMap不能保证映射的顺序,不保证映射的顺序一直不变。同时,HashMap的实现不是同步的,并且返回的迭代器都是快速失败的(fail-fast)。
2.源码注释
public class HashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>,
Cloneable, Serializable {
/*
* 默认的初始容量,必须是2的幂次
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
/*
* 最大容量
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/*
* 默认的加载因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/*
* 存储元素的数组
*/
transient Entry[] table;
/*
* HashMap的大小
*/
transient int size;
/*
* 进行扩容的门限值(容量*加载因子)
*/
int threshold;
/*
* 加载因子
*/
final float loadFactor;
/*
* HashMap修改次数的计数器,用于进行快速失败的检测
*/
transient volatile int modCount;
/*
* 带有初始容量与加载因子的构造函数
*/
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);
// 设置capacity为大于initialCapacity且是2的幂的最小值
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;
this.loadFactor = loadFactor;
threshold = (int) (capacity * loadFactor);
table = new Entry[capacity];
init();
}
// 带有初始容量与默认加载因子的构造函数
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
// 使用默认容量与加载因子的构造函数
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
threshold = (int) (DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
table = new Entry[DEFAULT_INITIAL_CAPACITY];
init();
}
/*
* 通过传入的Map创建一个HashMap,容量为默认容量(16)和(map.zise()/DEFAULT_LOAD_FACTORY)+1的较大者,
* 加载因子为0.75
*/
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);
}
/*
* 初始化方法(钩子方法) 所有的构造方法和伪构造方法(clone,readObject)将在HashMap初始化完成之后, 元素插入之前调用该方法
*/
void init() {
}
/*
* hash函数,防止质量较差的hash函数。 该方法主要作用是防止质量较差的哈希函数带来过多的冲突(碰撞)问题。
* Java中int值占4个字节,即32位。根据这32位值进行移位、异或运算得到一个值。
*/
static int hash(int h) {
// 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);
}
/*
* 根据hashcode计算index,
* 通过 h &(table.length -1) 来得到该对象的保存位置,因为 HashMap中数组的长度总是 2 的 n 次方,
* 当 length 总是 2 的倍数时,h & (length-1) 将是一个非常巧妙的设计:假设 h=5,length=16, 那么 h & length - 1 将得到 5;
* 如果 h=6,length=16, 那么 h & length - 1 将得到 6,如果 h=15,length=16, 那么 h & length - 1 将得到 15;但是当 h=16 时 ,
* length=16 时,那么 h & length - 1 将得到 0 了;当 h=17 时 , length=16 时,那么 h & length - 1 将得到 1 了,
* 这样保证计算得到的索引值总是位于 table 数组的索引之内。
*/
static int indexFor(int h, int length) {
return h & (length - 1);
}
//返回HashMap的大小
public int size() {
return size;
}
//返回HashMap是否为空
public boolean isEmpty() {
return size == 0;
}
/*
* 根据传入的key对象,获取相应的value
*/
public V get(Object key) {
//查找null的key
if (key == null)
return getForNullKey();
//重新计算hash值
int hash = hash(key.hashCode());
//遍历查找
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.equals(k)))
return e.value;
}
return null;
}
//查找nullkey
private V getForNullKey() {
//key为null时index为0,遍历相应的单链表
for (Entry<K, V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
//确认是否包含key对象
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
//根据key查找对应的元素,不存在返回null
final Entry<K, V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
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;
}
/*
* 在此映射中关联指定值与指定键。如果该映射以前包含了一个该键的映射关系,则旧值被替换。
*/
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
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;
}
//存储key为null的元素
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;
}
/*
* 在构造函数和伪构造函数(clone,readObject)中用来替代put方法。
* 与put的不同的是该方法不扩展数组,不检查map修改次数,方法体调用createEntry方法而非addEntry
*/
private void putForCreate(K key, V value) {
int hash = (key == null) ? 0 : hash(key.hashCode());
int i = indexFor(hash, table.length);
/**
* Look for preexisting entry for key. This will never happen for clone
* or deserialize. It will only happen for construction if the input Map
* is a sorted map whose ordering is inconsistent w/ equals.
*/
/*
* 只在构造函数中可能被调用,例如传入一个sorted map,替换已存在的key
*/
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;
}
}
//创建元素
createEntry(hash, key, value, i);
}
/*
* 将指定map中数据插入到当前map中
*/
private void putAllForCreate(Map<? extends K, ? extends V> m) {
for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m
.entrySet().iterator(); i.hasNext();) {
Map.Entry<? extends K, ? extends V> e = i.next();
putForCreate(e.getKey(), e.getValue());
}
}
//对HashMap进行重组扩容
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
//如果容量已经是最大,则将门限值设置为Integer.MAX_VALUE
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
Entry[] newTable = new Entry[newCapacity];
transfer(newTable);
table = newTable;
threshold = (int) (newCapacity * loadFactor);
}
//将当前数组中的元素复制到新的数组中,重新进行hash处理确定其位置,并且链表顺序会被倒置
void transfer(Entry[] newTable) {
Entry[] src = table;
int newCapacity = newTable.length;
for (int j = 0; j < src.length; j++) {
Entry<K, V> e = src[j];
if (e != null) {
src[j] = null;
do {
Entry<K, V> next = e.next;
int i = indexFor(e.hash, newCapacity);
e.next = newTable[i];
newTable[i] = e;
e = next;
} while (e != null);
}
}
}
//将指定map中的元素复制到当前HashMap中
public void putAll(Map<? extends K, ? extends V> m) {
int numKeysToBeAdded = m.size();
if (numKeysToBeAdded == 0)
return;
/*
* Expand the map if the map if the number of mappings to be added is
* greater than or equal to threshold. This is conservative; the obvious
* condition is (m.size() + size) >= threshold, but this condition could
* result in a map with twice the appropriate capacity, if the keys to
* be added overlap with the keys already in this map. By using the
* conservative calculation, we subject ourself to at most one extra
* resize.
* 这是一种保守做法,考虑会有key与当前相同的情况,避免扩大过大的容量
*/
if (numKeysToBeAdded > threshold) {
int targetCapacity = (int) (numKeysToBeAdded / loadFactor + 1);
//目标容量超过最大值, targetCapacity = MAXIMUM_CAPACITY;
if (targetCapacity > MAXIMUM_CAPACITY)
targetCapacity = MAXIMUM_CAPACITY;
//获取大于目标容量最小的2的冥,这就是信容量
int newCapacity = table.length;
while (newCapacity < targetCapacity)
newCapacity <<= 1;
//新容量大于当前数组长度,则扩容
if (newCapacity > table.length)
resize(newCapacity);
}
//遍历map中的数据,插入到当前的Hashmap中
for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m
.entrySet().iterator(); i.hasNext();) {
Map.Entry<? extends K, ? extends V> e = i.next();
put(e.getKey(), e.getValue());
}
}
//根据key对象删除元素
public V remove(Object key) {
Entry<K, V> e = removeEntryForKey(key);
return (e == null ? null : e.value);
}
//根据key对象删除对应的元素
final Entry<K, V> removeEntryForKey(Object key) {
//计算hash值
int hash = (key == null) ? 0 : hash(key.hashCode());
//计算index值
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++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}
return e;
}
//根据传入的Entry元素,删除在Hashmap中的对应映射
final Entry<K, V> removeMapping(Object o) {
if (!(o instanceof Map.Entry))
return null;
Map.Entry<K, V> entry = (Map.Entry<K, V>) o;
Object key = entry.getKey();
int hash = (key == null) ? 0 : hash(key.hashCode());
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;
if (e.hash == hash && e.equals(entry)) {
modCount++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}
return e;
}
//清空Hashmap
public void clear() {
modCount++;
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
//判断Hashmap中是否包含value值
public boolean containsValue(Object value) {
if (value == null)
return containsNullValue();
//遍历查找,方向从前向后,从链表头向表尾
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
for (Entry e = tab[i]; e != null; e = e.next)
if (value.equals(e.value))
return true;
return false;
}
//判断Hashmap中是否包含null值
private boolean containsNullValue() {
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
for (Entry e = tab[i]; e != null; e = e.next)
if (e.value == null)
return true;
return false;
}
//重写clone方法
public Object clone() {
HashMap<K, V> result = null;
try {
result = (HashMap<K, V>) super.clone();
} catch (CloneNotSupportedException e) {
// assert false;
}
result.table = new Entry[table.length];
result.entrySet = null;
result.modCount = 0;
result.size = 0;
result.init();
result.putAllForCreate(this);
return result;
}
//存储元素类,使用拉链法,实际上每个桶是一个单链表
static class Entry<K, V> implements Map.Entry<K, V> {
final K key;
V value;
Entry<K, V> next;
final int hash;
/**
* Creates new 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方法,两个元素key与value都相等时认为他们相等
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) {
}
}
//通过给定的key与value添加元素
void addEntry(int hash, K key, V value, int bucketIndex) {
//得到表头节点
Entry<K, V> e = table[bucketIndex];
//在表头插入节点,next指向原来的表头节点元素
table[bucketIndex] = new Entry<K, V>(hash, key, value, e);
//如果Hashmap大小超过门限值,则进行扩容
if (size++ >= threshold)
resize(2 * table.length);
}
//与addEntry相似,用于在构造map时或clone、deserialization时
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K, V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K, V>(hash, key, value, e);
size++;
}
//迭代器类,实现了Iterator接口
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;
}
final Entry<K, V> nextEntry() {
//迭代过程中不能对Hashmap进行修改,否则抛出ConcurrentModificationException
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;
}
}
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();
}
}
// Subclass overrides these to alter behavior of views' iterator() method
Iterator<K> newKeyIterator() {
return new KeyIterator();
}
Iterator<V> newValueIterator() {
return new ValueIterator();
}
Iterator<Map.Entry<K, V>> newEntryIterator() {
return new EntryIterator();
}
// Views
private transient Set<Map.Entry<K, V>> entrySet = null;
/**
* Returns a {@link Set} view of the keys contained in this map. The set is
* backed by the map, so changes to the map are reflected in the set, and
* vice-versa. If the map is modified while an iteration over the set is in
* progress (except through the iterator's own <tt>remove</tt> operation),
* the results of the iteration are undefined. The set supports element
* removal, which removes the corresponding mapping from the map, via the
* <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>,
* <tt>retainAll</tt>, and <tt>clear</tt> operations. It does not support
* the <tt>add</tt> or <tt>addAll</tt> operations.
*/
public Set<K> keySet() {
Set<K> ks = keySet;
return (ks != null ? ks : (keySet = new KeySet()));
}
private final class KeySet extends AbstractSet<K> {
public Iterator<K> iterator() {
return newKeyIterator();
}
public int size() {
return size;
}
public boolean contains(Object o) {
return containsKey(o);
}
public boolean remove(Object o) {
return HashMap.this.removeEntryForKey(o) != null;
}
public void clear() {
HashMap.this.clear();
}
}
/**
* Returns a {@link Collection} view of the values contained in this map.
* The collection is backed by the map, so changes to the map are reflected
* in the collection, and vice-versa. If the map is modified while an
* iteration over the collection is in progress (except through the
* iterator's own <tt>remove</tt> operation), the results of the iteration
* are undefined. The collection supports element removal, which removes the
* corresponding mapping from the map, via the <tt>Iterator.remove</tt>,
* <tt>Collection.remove</tt>, <tt>removeAll</tt>, <tt>retainAll</tt> and
* <tt>clear</tt> operations. It does not support the <tt>add</tt> or
* <tt>addAll</tt> operations.
*/
public Collection<V> values() {
Collection<V> vs = values;
return (vs != null ? vs : (values = new Values()));
}
private final class Values extends AbstractCollection<V> {
public Iterator<V> iterator() {
return newValueIterator();
}
public int size() {
return size;
}
public boolean contains(Object o) {
return containsValue(o);
}
public void clear() {
HashMap.this.clear();
}
}
/**
* Returns a {@link Set} view of the mappings contained in this map. The set
* is backed by the map, so changes to the map are reflected in the set, and
* vice-versa. If the map is modified while an iteration over the set is in
* progress (except through the iterator's own <tt>remove</tt> operation, or
* through the <tt>setValue</tt> operation on a map entry returned by the
* iterator) the results of the iteration are undefined. The set supports
* element removal, which removes the corresponding mapping from the map,
* via the <tt>Iterator.remove</tt>, <tt>Set.remove</tt>, <tt>removeAll</tt>
* , <tt>retainAll</tt> and <tt>clear</tt> operations. It does not support
* the <tt>add</tt> or <tt>addAll</tt> operations.
*
* @return a set view of the mappings contained in this map
*/
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());
}
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();
}
}
/**
* Save the state of the <tt>HashMap</tt> instance to a stream (i.e.,
* serialize it).
*
* @serialData The <i>capacity</i> of the HashMap (the length of the bucket
* array) is emitted (int), followed by the <i>size</i> (an int,
* the number of key-value mappings), followed by the key
* (Object) and value (Object) for each key-value mapping. The
* key-value mappings are emitted in no particular order.
*/
private void writeObject(java.io.ObjectOutputStream s) throws IOException {
Iterator<Map.Entry<K, V>> i = (size > 0) ? entrySet0().iterator()
: null;
// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
// Write out number of buckets
s.writeInt(table.length);
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
if (i != null) {
while (i.hasNext()) {
Map.Entry<K, V> e = i.next();
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
}
private static final long serialVersionUID = 362498820763181265L;
/**
* Reconstitute the <tt>HashMap</tt> instance from a stream (i.e.,
* deserialize it).
*/
private void readObject(java.io.ObjectInputStream s) throws IOException,
ClassNotFoundException {
// Read in the threshold, loadfactor, and any hidden stuff
s.defaultReadObject();
// Read in number of buckets and allocate the bucket array;
int numBuckets = s.readInt();
table = new Entry[numBuckets];
init(); // Give subclass a chance to do its thing.
// Read in size (number of Mappings)
int size = s.readInt();
// Read the keys and values, and put the mappings in the HashMap
for (int i = 0; i < size; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
putForCreate(key, value);
}
}
// These methods are used when serializing HashSets
int capacity() {
return table.length;
}
float loadFactor() {
return loadFactor;
}
}