JDK1.8 HashMap源码分析

一、HashMap概述

在JDK1.8之前,HashMap采用数组+链表实现,即使用链表处理冲突,同一hash值的链表都存储在一个链表里。但是当位于一个桶中的元素较多,即hash值相等的元素较多时,通过key值依次查找的效率较低。而JDK1.8中,HashMap采用数组+链表+红黑树实现,当链表长度超过阈值(8)时,将链表转换为红黑树,这样大大减少了查找时间。

下图中代表jdk1.8之前的hashmap结构,左边部分即代表哈希表,也称为哈希数组,数组的每个元素都是一个单链表的头节点,链表是用来解决冲突的,如果不同的key映射到了数组的同一位置处,就将其放入单链表中。(此图借用网上的图)

图一、jdk1.8之前hashmap结构图

jdk1.8之前的hashmap都采用上图的结构,都是基于一个数组和多个单链表,hash值冲突的时候,就将对应节点以链表的形式存储。如果在一个链表中查找其中一个节点时,将会花费O(n)的查找时间,会有很大的性能损失。到了jdk1.8,当同一个hash值的节点数不小于8时,不再采用单链表形式存储,而是采用红黑树,如下图所示(此图是借用的图)

图二、jdk1.8 hashmap结构图

二、重要的field

[java] view plain copy

  1. //table就是存储Node类的数组,就是对应上图中左边那一栏,
  2. /**
  3. * The table, initialized on first use, and resized as
  4. * necessary. When allocated, length is always a power of two.
  5. * (We also tolerate length zero in some operations to allow
  6. * bootstrapping mechanics that are currently not needed.)
  7. */
  8. transient Node<K,V>[] table;
  9. /**
  10. * The number of key-value mappings contained in this map.
  11. *  记录hashmap中存储键-值对的数量
  12. */
  13. transient int size;
  14. /**
  15. * hashmap结构被改变的次数,fail-fast机制
  16. */
  17. transient int modCount;
  18. /**
  19. * The next size value at which to resize (capacity * load factor).
  20. * 扩容的门限值,当size大于这个值时,table数组进行扩容
  21. */
  22. int threshold;
  23. /**
  24. * The load factor for the hash table.
  25. *
  26. */
  27. float loadFactor;
  28. /**
  29. * The default initial capacity - MUST be a power of two.
  30. * 默认初始化数组大小为16
  31. */
  32. static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  33. /**
  34. * The maximum capacity, used if a higher value is implicitly specified
  35. * by either of the constructors with arguments.
  36. * MUST be a power of two <= 1<<30.
  37. */
  38. static final int MAXIMUM_CAPACITY = 1 << 30;
  39. /**
  40. * The load factor used when none specified in constructor.
  41. * 默认装载因子,
  42. */
  43. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  44. /**
  45. * The bin count threshold for using a tree rather than list for a
  46. * bin.  Bins are converted to trees when adding an element to a
  47. * bin with at least this many nodes. The value must be greater
  48. * than 2 and should be at least 8 to mesh with assumptions in
  49. * tree removal about conversion back to plain bins upon
  50. * shrinkage.
  51. * 这是链表的最大长度,当大于这个长度时,链表转化为红黑树
  52. */
  53. static final int TREEIFY_THRESHOLD = 8;
  54. /**
  55. * The bin count threshold for untreeifying a (split) bin during a
  56. * resize operation. Should be less than TREEIFY_THRESHOLD, and at
  57. * most 6 to mesh with shrinkage detection under removal.
  58. */
  59. static final int UNTREEIFY_THRESHOLD = 6;
  60. /**
  61. * The smallest table capacity for which bins may be treeified.
  62. * (Otherwise the table is resized if too many nodes in a bin.)
  63. * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
  64. * between resizing and treeification thresholds.
  65. */
  66. static final int MIN_TREEIFY_CAPACITY = 64;

三、构造函数

[java] view plain copy

  1. //可以自己指定初始容量和装载因子
  2. public HashMap(int initialCapacity, float loadFactor) {
  3. if (initialCapacity < 0)
  4. throw new IllegalArgumentException("Illegal initial capacity: " +
  5. initialCapacity);
  6. if (initialCapacity > MAXIMUM_CAPACITY)
  7. initialCapacity = MAXIMUM_CAPACITY;
  8. if (loadFactor <= 0 || Float.isNaN(loadFactor))
  9. throw new IllegalArgumentException("Illegal load factor: " +
  10. loadFactor);
  11. this.loadFactor = loadFactor;
  12. //重新定义了扩容的门限
  13. this.threshold = tableSizeFor(initialCapacity);
  14. }
  15. /**
  16. * Returns a power of two size for the given target capacity.
  17. */
  18. static final int tableSizeFor(int cap) {
  19. int n = cap - 1;
  20. //先移位再或运算,最终保证返回值是2的整数幂
  21. n |= n >>> 1;
  22. n |= n >>> 2;
  23. n |= n >>> 4;
  24. n |= n >>> 8;
  25. n |= n >>> 16;
  26. return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
  27. }
  28. /**
  29. * Constructs an empty <tt>HashMap</tt> with the specified initial
  30. * capacity and the default load factor (0.75).
  31. *
  32. * @param  initialCapacity the initial capacity.
  33. * @throws IllegalArgumentException if the initial capacity is negative.
  34. */
  35. //当知道所要构建的数据容量的大小时,最好直接指定大小,提高效率
  36. public HashMap(int initialCapacity) {
  37. this(initialCapacity, DEFAULT_LOAD_FACTOR);
  38. }
  39. /**
  40. * Constructs an empty <tt>HashMap</tt> with the default initial capacity
  41. * (16) and the default load factor (0.75).
  42. */
  43. public HashMap() {
  44. this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
  45. }
  46. //将map直接放入hashmap中
  47. public HashMap(Map<? extends K, ? extends V> m) {
  48. this.loadFactor = DEFAULT_LOAD_FACTOR;
  49. putMapEntries(m, false);
  50. }
  51. final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
  52. int s = m.size();
  53. if (s > 0) {
  54. if (table == null) { // pre-size
  55. float ft = ((float)s / loadFactor) + 1.0F;
  56. int t = ((ft < (float)MAXIMUM_CAPACITY) ?
  57. (int)ft : MAXIMUM_CAPACITY);
  58. if (t > threshold)
  59. threshold = tableSizeFor(t);
  60. }
  61. else if (s > threshold)
  62. resize();
  63. for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
  64. K key = e.getKey();
  65. V value = e.getValue();
  66. putVal(hash(key), key, value, false, evict);
  67. }
  68. }
  69. }
  70. /**
  71. * Basic hash bin node, used for most entries.  (See below for
  72. * TreeNode subclass, and in LinkedMyHashMap for its Entry subclass.)
  73. */
  74. 在hashMap的结构图中,hash数组就是用Node型数组实现的,许多Node类通过next组成链表,key、value实际存储在Node内部类中。
  75. public static class Node<K,V> implements Map.Entry<K,V> {
  76. final int hash;
  77. final K key;
  78. V value;
  79. Node<K,V> next;
  80. Node(int hash, K key, V value, Node<K,V> next) {
  81. this.hash = hash;
  82. this.key = key;
  83. this.value = value;
  84. this.next = next;
  85. }
  86. public final K getKey()        { return key; }
  87. public final V getValue()      { return value; }
  88. public final String toString() { return key + "=" + value; }
  89. public final int hashCode() {
  90. return Objects.hashCode(key) ^ Objects.hashCode(value);
  91. }
  92. public final V setValue(V newValue) {
  93. V oldValue = value;
  94. value = newValue;
  95. return oldValue;
  96. }
  97. public final boolean equals(Object o) {
  98. if (o == this)
  99. return true;
  100. if (o instanceof Map.Entry) {
  101. Map.Entry<?,?> e = (Map.Entry<?,?>)o;
  102. if (Objects.equals(key, e.getKey()) &&
  103. Objects.equals(value, e.getValue()))
  104. return true;
  105. }
  106. return false;
  107. }
  108. }

四、重要的方法分析

1.put方法

[java] view plain copy

  1. /**
  2. * Associates the specified value with the specified key in thismap.
  3. * If the map previously contained a mapping for the key, the old
  4. * value is replaced.
  5. *
  6. */
  7. public V put(K key, V value) {
  8. return putVal(hash(key), key, value, false, true);
  9. }
  10. static final int hash(Object key) {
  11. int h;
  12. //key的值为null时,hash值返回0,对应的table数组中的位置是0
  13. return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
  14. }
  15. /**
  16. * Implements Map.put and related methods
  17. *
  18. * @param hash hash for key
  19. * @param key the key
  20. * @param value the value to put
  21. * @param onlyIfAbsent if true, don‘t change existing value
  22. * @param evict if false, the table is in creation mode.
  23. * @return previous value, or null if none
  24. */
  25. final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
  26. boolean evict) {
  27. Node<K,V>[] tab; Node<K,V> p; int n, i;
  28. //先将table赋给tab,判断table是否为null或大小为0,若为真,就调用resize()初始化
  29. if ((tab = table) == null || (n = tab.length) == 0)
  30. n = (tab = resize()).length;
  31. //通过i = (n - 1) & hash得到table中的index值,若为null,则直接添加一个newNode
  32. if ((p = tab[i = (n - 1) & hash]) == null)
  33. tab[i] = newNode(hash, key, value, null);
  34. else {
  35. //执行到这里,说明发生碰撞,即tab[i]不为空,需要组成单链表或红黑树
  36. Node<K,V> e; K k;
  37. if (p.hash == hash &&
  38. ((k = p.key) == key || (key != null && key.equals(k))))
  39. //此时p指的是table[i]中存储的那个Node,如果待插入的节点中hash值和key值在p中已经存在,则将p赋给e
  40. e = p;
  41. //如果table数组中node类的hash、key的值与将要插入的Node的hash、key不吻合,就需要在这个node节点链表或者树节点中查找。
  42. else if (p instanceof TreeNode)
  43. //当p属于红黑树结构时,则按照红黑树方式插入
  44. e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
  45. else {
  46. //到这里说明碰撞的节点以单链表形式存储,for循环用来使单链表依次向后查找
  47. for (int binCount = 0; ; ++binCount) {
  48. //将p的下一个节点赋给e,如果为null,创建一个新节点赋给p的下一个节点
  49. if ((e = p.next) == null) {
  50. p.next = newNode(hash, key, value, null);
  51. //如果冲突节点达到8个,调用treeifyBin(tab, hash),这个treeifyBin首先回去判断当前hash表的长度,如果不足64的话,实际上就只进行resize,扩容table,如果已经达到64,那么才会将冲突项存储结构改为红黑树。
  52. if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
  53. treeifyBin(tab, hash);
  54. break;
  55. }
  56. //如果有相同的hash和key,则退出循环
  57. if (e.hash == hash &&
  58. ((k = e.key) == key || (key != null && key.equals(k))))
  59. break;
  60. p = e;//将p调整为下一个节点
  61. }
  62. }
  63. //若e不为null,表示已经存在与待插入节点hash、key相同的节点,hashmap后插入的key值对应的value会覆盖以前相同key值对应的value值,就是下面这块代码实现的
  64. if (e != null) { // existing mapping for key
  65. V oldValue = e.value;
  66. //判断是否修改已插入节点的value
  67. if (!onlyIfAbsent || oldValue == null)
  68. e.value = value;
  69. afterNodeAccess(e);
  70. return oldValue;
  71. }
  72. }
  73. ++modCount;//插入新节点后,hashmap的结构调整次数+1
  74. if (++size > threshold)
  75. resize();//HashMap中节点数+1,如果大于threshold,那么要进行一次扩容
  76. afterNodeInsertion(evict);
  77. return null;
  78. }

[java] view plain copy

[java] view plain copy

  1. 2.扩容函数resize()分析

[java] view plain copy

  1. /**
  2. * Initializes or doubles table size.  If null, allocates in
  3. * accord with initial capacity target held in field threshold.
  4. * Otherwise, because we are using power-of-two expansion, the
  5. * elements from each bin must either stay at same index, or move
  6. * with a power of two offset in the new table.
  7. *
  8. * @return the table
  9. */
  10. final Node<K,V>[] resize() {
  11. Node<K,V>[] oldTab = table;//定义临时Node数组型变量,作为hash table
  12. //读取hash table的长度
  13. int oldCap = (oldTab == null) ? 0 : oldTab.length;
  14. int oldThr = threshold;//读取扩容门限
  15. int newCap, newThr = 0;//初始化新的table长度和门限值
  16. if (oldCap > 0) {
  17. //执行到这里,说明table已经初始化
  18. if (oldCap >= MAXIMUM_CAPACITY) {
  19. threshold = Integer.MAX_VALUE;
  20. return oldTab;
  21. }
  22. //二倍扩容,容量和门限值都加倍
  23. else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
  24. oldCap >= DEFAULT_INITIAL_CAPACITY)
  25. newThr = oldThr << 1; // double threshold
  26. }
  27. else if (oldThr > 0) // initial capacity was placed in threshold
  28. //用构造器初始化了门限值,将门限值直接赋给新table容量
  29. newCap = oldThr;
  30. else {
  31. // zero initial threshold signifies using defaults
  32. //老的table容量和门限值都为0,初始化新容量,新门限值,在调用hashmap()方式构造容器时,就采用这种方式初始化
  33. newCap = DEFAULT_INITIAL_CAPACITY;
  34. newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
  35. }
  36. if (newThr == 0) {
  37. //如果门限值为0,重新设置门限
  38. float ft = (float)newCap * loadFactor;
  39. newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
  40. (int)ft : Integer.MAX_VALUE);
  41. }
  42. threshold = newThr;//更新新门限值为threshold
  43. @SuppressWarnings({"rawtypes","unchecked"})
  44. //初始化新的table数组
  45. Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
  46. table = newTab;
  47. //当原来的table不为null时,需要将table[i]中的节点迁移
  48. if (oldTab != null) {
  49. for (int j = 0; j < oldCap; ++j) {
  50. Node<K,V> e;
  51. //取出链表中第一个节点保存,若不为null,继续下面操作
  52. if ((e = oldTab[j]) != null) {
  53. oldTab[j] = null;//主动释放
  54. if (e.next == null)
  55. //链表中只有一个节点,没有后续节点,则直接重新计算在新table中的index,并将此节点存储到新table对应的index位置处
  56. newTab[e.hash & (newCap - 1)] = e;
  57. else if (e instanceof TreeNode)
  58. //若e是红黑树节点,则按红黑树移动
  59. ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
  60. else { // preserve order
  61. //迁移单链表中的每个节点
  62. Node<K,V> loHead = null, loTail = null;
  63. Node<K,V> hiHead = null, hiTail = null;
  64. Node<K,V> next;
  65. do {
  66. //下面这段暂时没有太明白,通过e.hash & oldCap将链表分为两队,参考知乎上的一段解释
  67. /**
  68. * 把链表上的键值对按hash值分成lo和hi两串,lo串的新索引位置与原先相同[原先位
  69. * j],hi串的新索引位置为[原先位置j+oldCap];
  70. * 链表的键值对加入lo还是hi串取决于 判断条件if ((e.hash & oldCap) == 0),因为* capacity是2的幂,所以oldCap为10...0的二进制形式,若判断条件为真,意味着
  71. * oldCap为1的那位对应的hash位为0,对新索引的计算没有影响(新索引
  72. * =hash&(newCap-*1),newCap=oldCap<<2);若判断条件为假,则 oldCap为1的那位* 对应的hash位为1,
  73. * 即新索引=hash&( newCap-1 )= hash&( (oldCap<<2) - 1),相当于多了10...0,
  74. * 即 oldCap
  75. * 例子:
  76. * 旧容量=16,二进制10000;新容量=32,二进制100000
  77. * 旧索引的计算:
  78. * hash = xxxx xxxx xxxy xxxx
  79. * 旧容量-1 1111
  80. * &运算 xxxx
  81. * 新索引的计算:
  82. * hash = xxxx xxxx xxxy xxxx
  83. * 新容量-1 1 1111
  84. * &运算 y xxxx
  85. * 新索引 = 旧索引 + y0000,若判断条件为真,则y=0(lo串索引不变),否则y=1(hi串
  86. * 索引=旧索引+旧容量10000)
  87. */
  88. next = e.next;
  89. if ((e.hash & oldCap) == 0) {
  90. if (loTail == null)
  91. loHead = e;
  92. else
  93. loTail.next = e;
  94. loTail = e;
  95. }
  96. else {
  97. if (hiTail == null)
  98. hiHead = e;
  99. else
  100. hiTail.next = e;
  101. hiTail = e;
  102. }
  103. } while ((e = next) != null);
  104. if (loTail != null) {
  105. loTail.next = null;
  106. newTab[j] = loHead;
  107. }
  108. if (hiTail != null) {
  109. hiTail.next = null;
  110. newTab[j + oldCap] = hiHead;
  111. }
  112. }
  113. }
  114. }
  115. }
  116. return newTab;
  117. }

[java] view plain copy

  1. 3.get方法

[java] view plain copy

  1. /**
  2. * Returns the value to which the specified key is mapped,
  3. * or {@code null} if this map contains no mapping for the key.
  4. *
  5. * <p>More formally, if this map contains a mapping from a key
  6. * {@code k} to a value {@code v} such that {@code (key==null ? k==null :
  7. * key.equals(k))}, then this method returns {@code v}; otherwise
  8. * it returns {@code null}.  (There can be at most one such mapping.)
  9. *
  10. * <p>A return value of {@code null} does not <i>necessarily</i>
  11. * indicate that the map contains no mapping for the key; it‘s also
  12. * possible that the map explicitly maps the key to {@code null}.
  13. * The {@link #containsKey containsKey} operation may be used to
  14. * distinguish these two cases.
  15. *
  16. * @see #put(Object, Object)
  17. */
  18. public V get(Object key) {
  19. Node<K,V> e;
  20. return (e = getNode(hash(key), key)) == null ? null : e.value;
  21. }
  22. /**
  23. * Implements Map.get and related methods
  24. *
  25. * @param hash hash for key
  26. * @param key the key
  27. * @return the node, or null if none
  28. */
  29. final Node<K,V> getNode(int hash, Object key) {
  30. Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
  31. if ((tab = table) != null && (n = tab.length) > 0 &&
  32. (first = tab[(n - 1) & hash]) != null) {
  33. if (first.hash == hash && // always check first node
  34. ((k = first.key) == key || (key != null && key.equals(k))))
  35. return first;
  36. if ((e = first.next) != null) {
  37. //分为红黑树和链表查找两种
  38. if (first instanceof TreeNode)
  39. return ((TreeNode<K,V>)first).getTreeNode(hash, key);
  40. do {
  41. if (e.hash == hash &&
  42. ((k = e.key) == key || (key != null && key.equals(k))))
  43. return e;
  44. } while ((e = e.next) != null);
  45. }
  46. }
  47. return null;
  48. }
  49. /**
  50. * Returns <tt>true</tt> if this map contains a mapping for the
  51. * specified key.
  52. *
  53. * @param   key   The key whose presence in this map is to be tested
  54. * @return <tt>true</tt> if this map contains a mapping for the specified
  55. * key.
  56. */
  57. public boolean containsKey(Object key) {
  58. return getNode(hash(key), key) != null;
  59. }

[java] view plain copy

  1. 4.红黑树

[java] view plain copy

  1. /**
  2. * Entry for Tree bins. Extends LinkedMyHashMap.Entry (which in turn
  3. * extends Node) so can be used as extension of either regular or
  4. * linked node.
  5. */
  6. static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
  7. TreeNode<K,V> parent;  // red-black tree links
  8. TreeNode<K,V> left;
  9. TreeNode<K,V> right;
  10. TreeNode<K,V> prev;    // needed to unlink next upon deletion
  11. boolean red;
  12. TreeNode(int hash, K key, V val, Node<K,V> next) {
  13. super(hash, key, val, next);
  14. }
  15. //红黑树暂时还没有仔细研究,红黑树相关的增删改查操作后期再认真分析。

五、总结

仔细分析hashmap源码后,可以掌握很多常用的数据结构的用法。本次笔记只是记录了hashmap几个常用的方法,像红黑树、迭代器等还没有仔细研究,后面有时间会认真分析。

网友文章参考http://www.cnblogs.com/ToBeAProgrammer/p/4787761.html

http://wenku.baidu.com/link?url=AHcaJRmJofOxRbX6L8vKoYSW59Tl-GJexJjNUdEvHuAwDgRtPfCzHhVTO21v7BV0V-OTp7D0BC3sh2jdctV9RYnwhM_6w8SlZ9Np-cago-7

时间: 2024-12-14 21:34:20

JDK1.8 HashMap源码分析的相关文章

JDK1.7 HashMap 源码分析

概述 HashMap是Java里基本的存储Key.Value的一个数据类型,了解它的内部实现,可以帮我们编写出更高效的Java代码. 本文主要分析JDK1.7中HashMap实现,JDK1.8中的HashMap已经和这个不一样了,后面会再总结. 正文 HashMap概述 HashMap根据键的hashCode值获取存储位置,大多数情况下可以直接定位到它的值,因而具有很快的访问速度,但遍历顺序却是不确定的. HashMap最多只允许一条记录的键为null,允许多条记录的值为null.HashMap

jdk1.8 HashMap源码分析(resize函数)

// 扩容兼初始化 final Node<K, V>[] resize() { Node<K, V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length;// 数组长度 int oldThr = threshold;// 临界值 int newCap, newThr = 0; if (oldCap > 0) { // 扩容 if (oldCap >= MAXIMUM_CAPACITY)

HashMap源码分析--jdk1.8

JDK1.8 ArrayList源码分析--jdk1.8LinkedList源码分析--jdk1.8HashMap源码分析--jdk1.8 HashMap概述 ??1. HashMap是可以动态扩容的数组,基于数组.链表.红黑树实现的集合.??2. HashMap支持键值对取值.克隆.序列化,元素无序,key不可重复value可重复,都可为null.??3. HashMap初始默认长度16,超出扩容2倍,填充因子0.75f.??4.HashMap当链表的长度大于8的且数组大小大于64时,链表结构

HashMap实现原理(jdk1.7),源码分析

HashMap实现原理(jdk1.7),源码分析 ? HashMap是一个用来存储Key-Value键值对的集合,每一个键值对都是一个Entry对象,这些Entry被以某种方式分散在一个数组中,这个数组就是HashMap的主干. 一.几大常量 //默认容量 16 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //最大容量 static final int MAXIMUM_CAPACITY = 1 << 30; //默认负载因

【JAVA集合】HashMap源码分析(转载)

原文出处:http://www.cnblogs.com/chenpi/p/5280304.html 以下内容基于jdk1.7.0_79源码: 什么是HashMap 基于哈希表的一个Map接口实现,存储的对象是一个键值对对象(Entry<K,V>): HashMap补充说明 基于数组和链表实现,内部维护着一个数组table,该数组保存着每个链表的表头结点:查找时,先通过hash函数计算hash值,再根据hash值计算数组索引,然后根据索引找到链表表头结点,然后遍历查找该链表: HashMap数据

Java集合系列之HashMap源码分析

一.HashMap简介 HashMap是基于哈希表的Map接口实现的,它存储的是内容是键值对<key,value>映射.此类不保证映射的顺序,假定哈希函数将元素适当的分布在各桶之间,可为基本操作(get和put)提供稳定的性能. ps:本文中的源码来自jdk1.8.0_45/src. 1.重要参数 HashMap的实例有两个参数影响其性能. 初始容量:哈希表中桶的数量 加载因子:哈希表在其容量自动增加之前可以达到多满的一种尺度 当哈希表中条目数超出了当前容量*加载因子(其实就是HashMap的

Java集合之HashMap源码分析

一.HashMap简介 HashMap是基于哈希表的Map接口实现的,它存储的是内容是键值对<key,value>映射.此类不保证映射的顺序,假定哈希函数将元素适当的分布在各桶之间,可为基本操作(get和put)提供稳定的性能. ps:本文中的源码来自jdk1.8.0_45/src. 1.重要参数 HashMap的实例有两个参数影响其性能. 初始容量:哈希表中桶的数量 加载因子:哈希表在其容量自动增加之前可以达到多满的一种尺度 当哈希表中条目数超出了当前容量*加载因子(其实就是HashMap的

[Java] HashMap源码分析

1.概述 Hashmap继承于AbstractMap,实现了Map.Cloneable.java.io.Serializable接口.它的key.value都可以为null,映射不是有序的. Hashmap不是同步的,如果想要线程安全的HashMap,可以通过Collections类的静态方法synchronizedMap获得线程安全的HashMap. Map map = Collections.synchronizedMap(new HashMap()); (除了不同步和允许使用 null 之

HashMap源码分析(转载)

一.HashMap概述 HashMap基于哈希表的 Map 接口的实现.此实现提供所有可选的映射操作,并允许使用 null 值和 null 键.(除了不同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同.)此类不保证映射的顺序,特别是它不保证该顺序恒久不变. 值得注意的是HashMap不是线程安全的,如果想要线程安全的HashMap,可以通过Collections类的静态方法synchronizedMap获得线程安全的HashMap. Map map = Coll