//-----------------------------------------------------------------------------------
转载需注明出处:http://blog.csdn.net/chdjj
//-----------------------------------------------------------------------------------
注:以下源码基于jdk1.7.0_11
public interface Map<K,V> {//Map集合的顶级接口定义
// Query Operations
int size();
boolean isEmpty();
boolean containsKey(Object key);//是否包含指定键
boolean containsValue(Object value);//是否包含指定值
V get(Object key);
// Modification Operations
V put(K key, V value);
V remove(Object key);
// Bulk Operations
void putAll(Map<? extends K, ? extends V> m);//批量放置元素
void clear();
// Views
//三种视图
Set<K> keySet();//获取键集
Collection<V> values();//获取值集
Set<Map.Entry<K, V>> entrySet();//获取键值集合
interface Entry<K,V> {//Map的内部接口,代表一个键值对
K getKey();//获取键
V getValue(); //获取值
V setValue(V value);//设置值
boolean equals(Object o);
int hashCode();
}
// Comparison and hashing
boolean equals(Object o);
int hashCode();
}public abstract class AbstractMap<K,V> implements Map<K,V>
public boolean containsKey(Object key) {
Iterator<Map.Entry<K,V>> i = entrySet().iterator();//获得迭代器
if (key==null) {//判断key是否为空,分别处理
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (e.getKey()==null)//为空的话使用等号判断
return true;
}
} else {
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (key.equals(e.getKey()))//不为空的话使用equals方法判断
return true;
}
}
return false;
}
public boolean containsValue(Object value) {
Iterator<Entry<K,V>> i = entrySet().iterator();
if (value==null) {
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (e.getValue()==null)
return true;
}
} else {
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (value.equals(e.getValue()))
return true;
}
}
return false;
}首先是containsKey和containsValue方法,需要注意的是这里的key和value是允许为空的,也就是说其子类默认是支持null键和值的。这里的entrySet方法是个抽象方法:public abstract Set<Entry<K,V>> entrySet();
public V put(K key, V value) {
throw new UnsupportedOperationException();
} public V get(Object key) {
Iterator<Entry<K,V>> i = entrySet().iterator();
if (key==null) {//依然是根据键值是否为null做不同处理
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (e.getKey()==null)
return e.getValue();
}
} else {
while (i.hasNext()) {
Entry<K,V> e = i.next();
if (key.equals(e.getKey()))
return e.getValue();
}
}
return null;
}public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable static final int DEFAULT_INITIAL_CAPACITY = 16;//默认初始容量
static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量为2的30次方
static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认装载因子为0.75
transient Entry<K,V>[] table;//桶数组,存放键值对
transient int size;//实际存储的键值对个数
int threshold;//HashMap的阈值,用于判断是否需要调整HashMap的容量(threshold = 容量*加载因子)
final float loadFactor;//装载因子
transient int modCount;//hashmap被改变的次数
static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE; 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);
// Find a power of 2 >= initialCapacity
//找出“大于initialCapacity”的最小的2的幂
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;
this.loadFactor = loadFactor;
threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
//初始化桶数组
table = new Entry[capacity];
useAltHashing = sun.misc.VM.isBooted() &&
(capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
init();//一个钩子函数,默认实现是空
}
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {//使用默认的初始容量和默认的加载因子构造HashMap
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
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);
}
// internal utilities
void init() {
} static class Entry<K,V> implements Map.Entry<K,V> {//实现Map.Entry接口
final K key;//键,final类型,不可更改/
V value;//值
Entry<K,V> next;//HashMap通过链表法解决冲突,这里的next指向链表的下一个元素
int hash;//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;
}
//允许设置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() {//键为空则hash值为0,否则通过通过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) {
}
} public V put(K key, V value) {//向集合中添加一个键值对
if (key == null)//如果键为空,则调用putForNullKey
return putForNullKey(value);
int hash = hash(key);//否则根据key生成一个hash索引值
int i = indexFor(hash, table.length);//在根据索引值找到插入位置
//循环遍历指定位置的Entry链表,若找到一个键与当前键完全一致的Entry,那么覆盖原来的键所对应的值,并返回原值
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
//hash值相同且键相同
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;
} private V putForNullKey(V value) {
//空键,其hash值为0,必然存储在数组的0索引位置上。
//我们需要遍历0位置的entry链表,如果已经有一个null键了,那么也是覆盖
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;
} final int hash(Object k) {//根据键生成hash值
int h = 0;
if (useAltHashing) {
if (k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h = hashSeed;
}
h ^= k.hashCode();
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
//根据hash值计算键在桶数组的位置
static int indexFor(int h, int length) {
return h & (length-1);//由put方法可知,这个length就是数组长度,而且由构造器发现数组长度始终为2的整数次方,那么这个&操作实际上就是是h%length的高效表示方式,可以使结果小于数组长度.
}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);
}
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];//获取原来在该位置上的Entry对象
table[bucketIndex] = new Entry<>(hash, key, value, e);//将当前的键值插到该位置,并作为链表的起始结点。其next指针指向先前的Entry
size++;
}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;
transfer(newTable, rehash);//将原数组中所有键值对转移至新数组
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) {//需遍历每个Entry,耗时
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;
}
}
}public V get(Object key) {
if (key == null)//若键为空
return getForNullKey();
Entry<K,V> entry = getEntry(key);//获取Entry对象
//未找到就返回null,否则返回键所对应的值
return null == entry ? null : entry.getValue();
} private V getForNullKey() {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}而这个getEntry方法就是通过键生成hash值,然后得到其在数组的索引位,查找该位置的链表,找到第一个满足的键,并返会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) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.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++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}
return e;
} public void clear() {
modCount++;
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)//遍历数组
tab[i] = null;//置空
size = 0;
}
【源码】HashMap源码剖析,布布扣,bubuko.com
原文:http://blog.csdn.net/chdjj/article/details/38553163