[关闭]
@pastqing 2016-04-12T13:23:27.000000Z 字数 9113 阅读 2259

java集合框架——Map(一)

java java-collection-framwork


一、HashMap的基本特性

读完JDK源码HashMap.class中的注释部分,可以总结出很多HashMap的特性。

二、Hash table 数据结构分析

Hash table(散列表,哈希表),是根据关键字而直接访问内存存储位置的数据结构。也就是说散列表建立了关键字和存储地址之间的一种直接映射

如下图, key经过散列函数得到buckets的一个索引位置。
Hash_table.png-9.5kB

通过散列函数获取index不可避免会出现相同的情况,也就是冲突。下面简单介绍几种解决冲突的方法:

JDK中的HashMap解决冲突的方法就是用的Separate chaining法。

三、HashMap源码分析(JDK1.7)

1、HashMap读写元素

  1. static class Entry<K,V> implements Map.Entry<K,V> {
  2. final K key;
  3. V value;
  4. Entry<K,V> next;
  5. int hash;
  6. Entry(int h, K k, V v, Entry<K,V> n) {
  7. value = v;
  8. next = n;
  9. key = k;
  10. hash = h;
  11. }
  12. //key, value的get与set方法省略,get与set操作会在后面的迭代器中用到
  13. ...
  14. public final boolean equals(Object o) {
  15. if (!(o instanceof Map.Entry))
  16. return false;
  17. Map.Entry e = (Map.Entry)o;
  18. Object k1 = getKey();
  19. Object k2 = e.getKey();
  20. if (k1 == k2 || (k1 != null && k1.equals(k2))) {
  21. Object v1 = getValue();
  22. Object v2 = e.getValue();
  23. if (v1 == v2 || (v1 != null && v1.equals(v2)))
  24. return true;
  25. }
  26. return false;
  27. }
  28. //此处将Key的hashcode与Value的hashcode做亦或运算得到Entry的hashcode
  29. public final int hashCode() {
  30. return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
  31. }
  32. public final String toString() {
  33. return getKey() + "=" + getValue();
  34. }
  35. /**
  36. * This method is invoked whenever the value in an entry is
  37. * overwritten by an invocation of put(k,v) for a key k that's already
  38. * in the HashMap.
  39. */
  40. void recordAccess(HashMap<K,V> m) {
  41. }
  42. /**
  43. * This method is invoked whenever the entry is
  44. * removed from the table.
  45. */
  46. void recordRemoval(HashMap<K,V> m) {
  47. }
  48. }

一个Entry包括key, value, hash以及下一个Entry的引用, 很明显这是个单链表, 其实现了Map.Entry接口。

recordAcess(HashMap<K, V>recordRemoval(HashMap<K, V>)在HashMap中是没有任何具体实现的。但是在LinkedHashMap这两个方法用来实现LRU算法。

  1. public V get(Object key) {
  2. //key是null的情况
  3. if (key == null)
  4. return getForNullKey();
  5. //根据key查找Entry
  6. Entry<K,V> entry = getEntry(key);
  7. return null == entry ? null : entry.getValue();
  8. }

getForNullKey源码

  1. private V getForNullKey() {
  2. if (size == 0) {
  3. return null;
  4. }
  5. //遍历冲突链
  6. for (Entry<K,V> e = table[0]; e != null; e = e.next) {
  7. if (e.key == null)
  8. return e.value;
  9. }
  10. return null;
  11. }

key为Null的Entry存放在table[0]中,但是table[0]中的冲突链中不一定存在key为null, 因此需要遍历。

根据key获取entry:

  1. final Entry<K,V> getEntry(Object key) {
  2. if (size == 0) {
  3. return null;
  4. }
  5. int hash = (key == null) ? 0 : hash(key);
  6. //通过hash得到table中的索引位置,然后遍历冲突链表找到Key
  7. for (Entry<K,V> e = table[indexFor(hash, table.length)];
  8. e != null;
  9. e = e.next) {
  10. Object k;
  11. if (e.hash == hash &&
  12. ((k = e.key) == key || (key != null && key.equals(k))))
  13. return e;
  14. }
  15. return null;
  16. }

以上就是HashMap读取一个Entry的过程及其源码。时间复杂度O(1)

  1. public V put(K key, V value) {
  2. //空表table的话,根据size的阈值填充
  3. if (table == EMPTY_TABLE) {
  4. inflateTable(threshold);
  5. }
  6. //填充key为Null的Entry
  7. if (key == null)
  8. return putForNullKey(value);
  9. //生成hash,得到索引Index的映射
  10. int hash = hash(key);
  11. int i = indexFor(hash, table.length);
  12. //遍历当前索引的冲突链,找是否存在对应的key
  13. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  14. Object k;
  15. //如果存在对应的key, 则替换oldValue并返回oldValue
  16. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
  17. V oldValue = e.value;
  18. e.value = value;
  19. e.recordAccess(this);
  20. return oldValue;
  21. }
  22. }
  23. //冲突链中不存在新写入的Entry的key
  24. modCount++;
  25. //插入一个新的Entry
  26. addEntry(hash, key, value, i);
  27. return null;
  28. }

addEntry与createEntry源码:

  1. void addEntry(int hash, K key, V value, int bucketIndex) {
  2. //插入新Entry前,先对当前HashMap的size和其阈值大小的判断,选择是否扩容
  3. if ((size >= threshold) && (null != table[bucketIndex])) {
  4. resize(2 * table.length);
  5. hash = (null != key) ? hash(key) : 0;
  6. bucketIndex = indexFor(hash, table.length);
  7. }
  8. createEntry(hash, key, value, bucketIndex);
  9. }
  1. void createEntry(int hash, K key, V value, int bucketIndex) {
  2. Entry<K,V> e = table[bucketIndex];
  3. //头插法,新写入的entry插入当前索引位置的冲突链第一个Entry的前面
  4. table[bucketIndex] = new Entry<>(hash, key, value, e);
  5. size++;
  6. }

以上就是HashMap写入一个Entry的过程及其源码。时间复杂度O(1)

  1. final Entry<K,V> removeEntryForKey(Object key) {
  2. if (size == 0) {
  3. return null;
  4. }
  5. //根据key计算hash值,获取索引
  6. int hash = (key == null) ? 0 : hash(key);
  7. int i = indexFor(hash, table.length);
  8. //链表的删除,定义两个指针,pre表示前驱
  9. Entry<K,V> prev = table[i];
  10. Entry<K,V> e = prev;
  11. //遍历冲突链,删除所有为key的Enrty
  12. while (e != null) {
  13. Entry<K,V> next = e.next;
  14. Object k;
  15. //找到了
  16. if (e.hash == hash &&
  17. ((k = e.key) == key || (key != null && key.equals(k)))) {
  18. modCount++;
  19. size--;
  20. //找到第一个结点就是要删除的结点
  21. if (prev == e)
  22. table[i] = next;
  23. else
  24. prev.next = next;
  25. e.recordRemoval(this);
  26. return e;
  27. }
  28. prev = e;
  29. e = next;
  30. }
  31. return e;
  32. }

以上就是HashMap删除一个Entry的过程及其源码。时间复杂度O(1)

2、HashMap的哈希原理(hash function)

HashMap中散列函数的实现是通过hash(Object k)indexFor(int h, int length)完成, 下面看下源码:

  1. final int hash(Object k) {
  2. int h = hashSeed;
  3. if (0 != h && k instanceof String) {
  4. return sun.misc.Hashing.stringHash32((String) k);
  5. }
  6. h ^= k.hashCode();
  7. // This function ensures that hashCodes that differ only by
  8. // constant multiples at each bit position have a bounded
  9. // number of collisions (approximately 8 at default load factor).
  10. //为了降低冲突的几率
  11. h ^= (h >>> 20) ^ (h >>> 12);
  12. return h ^ (h >>> 7) ^ (h >>> 4);
  13. }

获取Index索引源码:

  1. static int indexFor(int h, int length) {
  2. // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
  3. return h & (length-1);
  4. }

HashMap通过一个hash function将key映射到[0, table.length]的区间内的索引。这样的索引方法大体有两种:

  1. hash(key) % table.length, 其中length必须为素数。JDK中HashTable利用此实现方式。
    具体使用素数的原因,可以查找相关算法资料证明,这里不再陈述。

  2. hash(key) & (table.length - 1 ) 其中length必须为2指数次方。JDK中HashMap利用此实现方式。
    因为length的大小为2指数次方倍, 因此 hash(key) & (table.length - 1)总会在[0, length - 1]之间。但是仅仅这样做的话会出现问题一个冲突很大的问题,因为JAVA中hashCode的值为32位,当HashMap的容量偏小,例如16时,做异或运算时,高位总是被舍弃,低位运算后却增加了冲突发生的概率。

因此为了降低冲突发生的概率, 代码中做了很多位运算以及异或运算

3、HashMap内存分配策略

  1. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  2. static final int MAXIMUM_CAPACITY = 1 << 30;
  3. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  1. public HashMap(int initialCapacity, float loadFactor) {
  2. if (initialCapacity < 0)
  3. throw new IllegalArgumentException("Illegal initial capacity: " +
  4. initialCapacity);
  5. if (initialCapacity > MAXIMUM_CAPACITY)
  6. initialCapacity = MAXIMUM_CAPACITY;
  7. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  8. throw new IllegalArgumentException("Illegal load factor: " +
  9. loadFactor);
  10. this.loadFactor = loadFactor;
  11. threshold = initialCapacity;
  12. init();
  13. }

之前说过HashMap中capacity必须是2的指数倍, 构造函数里并没有限制,那如何保证保证capacity的值是2的指数倍呢
put操作时候,源码中会判断目前的哈希表是否是空表,如果是则调用inflateTable(int toSize)

  1. private void inflateTable(int toSize) {
  2. // Find a power of 2 >= toSize
  3. int capacity = roundUpToPowerOf2(toSize);
  4. threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
  5. table = new Entry[capacity];
  6. initHashSeedAsNeeded(capacity);
  7. }

其中roundUpToPowerOf2就是获取大于等于给定参数的最小的2的n次幂

  1. private static int roundUpToPowerOf2(int number) {
  2. // assert number >= 0 : "number must be non-negative";
  3. return number >= MAXIMUM_CAPACITY
  4. ? MAXIMUM_CAPACITY
  5. : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
  6. }

Integer.hightestOneBit(int)是将给定参数的最高位的1保留,剩下的变为0的操作,简单说就是将参数int变为小于等于它的最大的2的n次幂。

number为2的n次幂,减1后最高位处于原来的次高位, 再左移1位仍然可以定位到最高位位置
number不是2的n次幂,减1左移1位后最高位仍是原来的最高位

  1. void resize(int newCapacity) {
  2. Entry[] oldTable = table;
  3. int oldCapacity = oldTable.length;
  4. //哈希表已达到最大容量,1 << 30
  5. if (oldCapacity == MAXIMUM_CAPACITY) {
  6. threshold = Integer.MAX_VALUE;
  7. return;
  8. }
  9. Entry[] newTable = new Entry[newCapacity];
  10. //将oldTable中的Entry转移到newTable中
  11. //initHashSeedAsNeeded的返回值决定是否重新计算hash值
  12. transfer(newTable, initHashSeedAsNeeded(newCapacity));
  13. table = newTable;
  14. //重新计算threshold
  15. threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
  16. }
  1. void transfer(Entry[] newTable, boolean rehash) {
  2. int newCapacity = newTable.length;
  3. //遍历oldTable
  4. for (Entry<K,V> e : table) {
  5. //遍历冲突链
  6. while(null != e) {
  7. Entry<K,V> next = e.next;
  8. if (rehash) {
  9. //重新计算hash值
  10. e.hash = null == e.key ? 0 : hash(e.key);
  11. }
  12. int i = indexFor(e.hash, newCapacity);
  13. //将元素插入到头部,头插法
  14. e.next = newTable[i];
  15. newTable[i] = e;
  16. e = next;
  17. }
  18. }
  19. }

以上就是HashMap内存分配的整个过程,总结说来就是,hashMap在put一个Entry的时候会检查当前容量与threshold的大小来选择是否扩容。每次扩容的大小是2 * table.length。在扩容期间会根据initHashSeedAsNeeded判断是否需要重新计算hash值。

四、HashMap的迭代器

HashMap中的ValueIterator, KeyIterator, EntryIterator等迭代器都是基于HashIterator的,下面看下它的源码:

  1. private abstract class HashIterator<E> implements Iterator<E> {
  2. Entry<K,V> next; // next entry to return
  3. int expectedModCount; // For fast-fail
  4. int index; // current slot,table index
  5. Entry<K,V> current; // current entry
  6. HashIterator() {
  7. expectedModCount = modCount;
  8. //在哈希表中找到第一个Entry
  9. if (size > 0) {
  10. Entry[] t = table;
  11. while (index < t.length && (next = t[index++]) == null)
  12. ;
  13. }
  14. }
  15. public final boolean hasNext() {
  16. return next != null;
  17. }
  18. final Entry<K,V> nextEntry() {
  19. //HashMap是非线程安全的,遍历时仍然先判断是否有表结构的修改
  20. if (modCount != expectedModCount)
  21. throw new ConcurrentModificationException();
  22. Entry<K,V> e = next;
  23. if (e == null)
  24. throw new NoSuchElementException();
  25. if ((next = e.next) == null) {
  26. //找到下一个Entry
  27. Entry[] t = table;
  28. while (index < t.length && (next = t[index++]) == null)
  29. ;
  30. }
  31. current = e;
  32. return e;
  33. }
  34. public void remove() {
  35. if (current == null)
  36. throw new IllegalStateException();
  37. if (modCount != expectedModCount)
  38. throw new ConcurrentModificationException();
  39. Object k = current.key;
  40. current = null;
  41. HashMap.this.removeEntryForKey(k);
  42. expectedModCount = modCount;
  43. }
  44. }

Key, Value, Entry这个三个迭代器进行封装就变成了keySet, values, entrySet三种集合视角。这三种集合视角都支持对HashMap的remove, removeAll, clear操作,不支持add, addAll操作。

以上就是HashMap的简要分析。

参考文献
Wiki HashTable
HashMap源码分析

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注