HashMap源码分析
2015-11-22 17:16
393 查看
1.结构
HashMap和List一样在实际应用中非常常见,但对其结构可能不太熟,本篇使用JDK1.7中的HashMap和HashSet进行源码解析,就当是自己做的笔记吧.首先看下HashMap和HashSet的结构如下:
这个结构说明了Map集合不在Java Collection框架中,而是一个单独存在的接口.
Set接口和Map接口本身没什么联系.
2.HashMap
2.1 内部结构
HashMap 的内部结构有一个transient Entry table;该对象和ArrayList中的elementData一样是由transient修饰的.其中的Enrty类部分信息如下: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都是一个链表,该结构描绘了map的结构,如下图:
这里只是假设数据是这样的,其中table[0] = entry1,table[1] = null,table[2] = entry,table.length = 16.
其中的entry1.next = enrty1.1,entry3.next = entry3.1,entry3.1.next = entry3.2
在这里table的每一个元素都维护了一个链表.
2.2 字段
private static final long serialVersionUID = 362498820763181265L; static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 static final int MAXIMUM_CAPACITY = 1 << 30; static final float DEFAULT_LOAD_FACTOR = 0.75f; static final Entry<?,?>[] EMPTY_TABLE = {}; transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE; transient int size; int threshold; final float loadFactor; transient int modCount; static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE; transient int hashSeed = 0;
serialVersionUID:分配的序列化ID值
DEFAULT_INITIAL_CAPACITY:默认初始化的集合大小,在这里是2^4=16
MAXIMUM_CAPACITY:最大的集合大小,默认是2^30
DEFAULT_LOAD_FACTOR:默认的加载因子,代表:存放的元素总数/散列桶数=0.75
EMPTY_TABLE:空的Entry[]
table:存放元素的Entry[],默认是空的,可以理解成是一个散列桶
size:存放元素的大小
threshold:最多可存放的元素,该值即:table.lenght * 加载因子
loadFactor:加载因子
modCount:和ArrayList中的一样,用于迭代集合时的标志位
ALTERNATIVE_HASHING_THRESHOLD_DEFAULT和hashSeed 暂且不清楚什么作用.
2.3 构造器
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); this.loadFactor = loadFactor; threshold = initialCapacity; init(); }
一般在使用的时候都是默认的构造器,其threshold=16,加载因子为0.75.也可以通过第三个构造器初始化想要的大小.
2.4 put方法
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); 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; }
put方法比较麻烦,我们分不同情形分析:
2.4.1.table == null
table为空,说明是刚刚创建Map.比如: Map map = new HashMap();map.put(“1”);此时执行inflateTable(threshold) 如下:
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); }
由于默认的threshold=16,故toSize=16,其中的roundUpToPowerOf2(toSize) 方法如下:
private static int roundUpToPowerOf2(int number) { // assert number >= 0 : "number must be non-negative"; return number >= MAXIMUM_CAPACITY ? MAXIMUM_CAPACITY : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1; }
Integer.highestOneBit(i)方法表示取得i的最高位,在这里number - 1 的最高位是8,在执行<<1的话是16,返回结果为16.
继续上述程序可知,threshold=16*0.75=12,table.length=16.由此创建了table实体.
2.4.2 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; }
这段程序说明Map集合可以存放null的key,空的key是只存放在table[0]中,modCount++可见上几篇的描述.addEntry方法后续介绍.
2.4.3 key != null
按照上述程序的进行,如下: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)是一种均匀散列算法,具体可看:http://www.cnblogs.com/chengxuyuandashu/p/3575049.html?utm_source=tuicool&utm_medium=referral
indexFor方法如下:
static int indexFor(int h, int length) { return h & (length-1); }
这个方法的作用是根据求出的hash值与table的长度相与,找到该存放的table下标.
在for循环中只在对应的table下标中的链表进行迭代,找到key,赋值.没找到的话,执行最后的添加语句
modCount++;addEntry(hash, key, value, i);
2.4.4 addEntry
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); }
传进来的参数包含,计算出的hash值,key,value,table相应的位置i.
首先判断如果存的元素个数是否超出最大存储范围.
如果超过执行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); }
在这里很明显将table的长度扩大为原来的2倍,transfer方法是将原来的table数据存放到新的数组中去.当扩充完后,重新计算一下hash 和bucketIndex.
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++; }
这个方法也好理解,就是将原来对应位置链表的头改为新添加进来的entry,这样新添加进来的entry位于最前面.至此整个put方法结束.
2.5 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; }
getEntry很好理解,根据key值得到hash值,再找到相应的table下表,遍历列表找出对应的entry.
remove方法类似,故不再贴出.
2.6 containsValue方法
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; }
该方法双重循环迭代每一个entry,判断value值是否相等.
2.7 Iterator()
HashMap的迭代器只要是2个方法hasNext()和Iterator().如下:public final boolean hasNext() { return next != null; } 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; }
其中的nextEntry方法中的while (index < t.length && (next = t[index++]) == null)
;是寻找下一个具有值得table下标.
3.HashSet
private transient HashMap<E,Object> map; private static final Object PRESENT = new Object(); public HashSet() { map = new HashMap<>(); } public boolean add(E e) { return map.put(e, PRESENT)==null; } public Iterator<E> iterator() { return map.keySet().iterator(); }
HashSet的实现都是由HashMap帮忙的,他只存储了Key的值.这有一些应用场景.比如:HashSet set = new HashSet(new ArrayList());这样可以将ArrayList去重.
相关文章推荐
- 【Java多线程编程】主线程对其他线程的控制
- mac下的软件安装homebrew
- List集合之ArrayList
- PackageManager详解
- thinkphp框架学习
- Java中StringBuffer字符串缓冲类和System,RunTime类等
- C#中变量命名规则
- 改变struts中表单提交后url后缀名
- nyoj 814 又见拦截导弹
- Java基本代码
- 显示列表
- 【codevs1087&&NOIP2003】麦森数,高精度+对数+快速幂
- Hibernate 映射关系 ---One2Many 双向关联
- MySQL 触发器简单实例
- WA题集
- ARP欺骗与MITM(中间人攻击)实例
- Php 笔记
- 【Effective C++】继承与面向对象设计
- CF#301 D:Bad Luck Island (概率dp)
- 爱因斯坦名言收藏