HashMap

2018-07-12  本文已影响0人  粪球滚屎壳螂

面试问候语—HashMap

HashMap简直就像问候语一样,面试官问一个HashMap,应聘者呢回答一下表示相互的尊敬。

/**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

 /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
    static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

Node 为HashMap中的一个内部类实现了Entry<K,V>接口。也可以理解为Node就是一个Entry。HashMap中的key-value都是存储在Node数组table中的。
还有一些需要关注的参数:

   /**
     * The default initial capacity - MUST be a power of two.
     * 默认初始化的容量为16,必须是2的幂。  1 << 4  运算的结果就是16 即默认值为 16
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30. 
     * 初始化的最大值 1 << 30 计算结果为 1073741824
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     * 默认的装载因子是0.75 
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     * 一个桶(bucket)中的数据结构由链表转换成树的阈值。
     * 即当桶中bin的数量超过TREEIFY_THRESHOLD时使用树来代替链表。默认值是8 
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     * 当执行resize操作时,桶中的数据结构由树变成链表的阀值,
     * 当桶中bin的数量少于UNTREEIFY_THRESHOLD时使用链表来代替树。默认值是6 
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     * 当哈希表中的容量大于这个值时,表中的桶才能进行树形化
     * 否则桶内元素太多时会扩容,而不是树形化
     * 为了避免进行扩容、树形化选择的冲突,这个值不能小于 4 * TREEIFY_THRESHOLD
     */
    static final int MIN_TREEIFY_CAPACITY = 64;

除了这些默认参数之外还有两个很特殊的参数

/**
   * The next size value at which to resize (capacity * load factor).
   * 当前HashMap的容量阀值,超过则需要扩容
   * @serial
   */
  // (The javadoc description is true upon serialization.
  // Additionally, if the table array has not been allocated, this
  // field holds the initial array capacity, or zero signifying
  // DEFAULT_INITIAL_CAPACITY.)
  int threshold;

  /**
   * The load factor for the hash table.
   *
   * @serial
   */
  final float loadFactor;

阅读源码可以发现当创建HashMap时调用了构造函数:

 /**
   * Constructs an empty <tt>HashMap</tt> with the specified initial
   * capacity and load factor.
   *
   * @param  initialCapacity the initial capacity
   * @param  loadFactor      the load factor
   * @throws IllegalArgumentException if the initial capacity is negative
   *         or the load factor is nonpositive
   */
  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;
      this.threshold = tableSizeFor(initialCapacity);
  }

时,最终的结果并不是简单的又注释中所说的(capacity * load factor)而是调用了方法tableSizeFor(int cap),这方法全是位运算,其实转化为二进制然后详细看一下也能看懂个大概
,与之相似的还有HashMap的hashCode()方法和计算桶的位置时的取余。

/**
     * Returns a power of two size for the given target capacity.
     * 根据传入的数字,返回一个与之对应值的下一个2的幂
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

装载因子这个参数影响到了整个HashMap中桶的数量,桶数设定为预计元素总数的 75%-150%。所以说在预定元素总数不变的情况下,并且容量没到扩容阀值的情况下,负载因子增大,能容纳的元素增多,每个桶分得的元素就增多,冲突的几率增大,插入和查找的效率都降低,反之,负载因子减小,能容纳的元素减少,每个桶分得的元素就较少,冲突的概率减小,插入和查找的效率都提高。所以装载因子关系到整个HashMap的效率,默认值应该是一个折中的选择。

简单读一个put方法的源码:

/**
    * Associates the specified value with the specified key in this map.
    * If the map previously contained a mapping for the key, the old
    * value is replaced.
    *
    * @param key key with which the specified value is to be associated
    * @param value value to be associated with the specified key
    * @return the previous value associated with <tt>key</tt>, or
    *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
    *         (A <tt>null</tt> return can also indicate that the map
    *         previously associated <tt>null</tt> with <tt>key</tt>.)
    */
   public V put(K key, V value) {
       return putVal(hash(key), key, value, false, true);
   }
   
   /**
    * Implements Map.put and related methods
    *
    * @param hash hash for key
    * @param key the key
    * @param value the value to put
    * @param onlyIfAbsent if true, don't change existing value
    * @param evict if false, the table is in creation mode.
    * @return previous value, or null if none
    */
   final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
       Node<K,V>[] tab; Node<K,V> p; int n, i;
       //如果保存的数据的table为空或者长度为0则初始化table
       if ((tab = table) == null || (n = tab.length) == 0)
           n = (tab = resize()).length;
       //如果当前table节点,即当前元素应该保存的桶是空的则创建一个新的节点保存元素   
       if ((p = tab[i = (n - 1) & hash]) == null)
           tab[i] = newNode(hash, key, value, null);
       else {
           Node<K,V> e; K k;
           //如果在当前桶中的头节点存在与当前元素完全相等的元素则直接跳过插入逻辑
           if (p.hash == hash &&
               ((k = p.key) == key || (key != null && key.equals(k))))
               e = p;
           //如果当前节点已经是一个树节点则调用树的插入逻辑    
           else if (p instanceof TreeNode)
               e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
           //否则遍历当前桶中的数据    
           else {
               for (int binCount = 0; ; ++binCount) {
                   //假如未找到待插入元素相同的元素 则新建节点插入
                   if ((e = p.next) == null) {
                       p.next = newNode(hash, key, value, null);
                       //如果当前桶中的元素大于TREEIFY_THRESHOLD 则将其转化为一个树
                       if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                           treeifyBin(tab, hash);
                       break;
                   }
                   //如果找到相同元素则直接跳过逻辑
                   if (e.hash == hash &&
                       ((k = e.key) == key || (key != null && key.equals(k))))
                       break;
                   p = e;
               }
           }
           //如果存在则继续后续逻辑
           if (e != null) { // existing mapping for key
               V oldValue = e.value;
               if (!onlyIfAbsent || oldValue == null)
                   e.value = value;
               afterNodeAccess(e);
               return oldValue;
           }
       }
       //累加操作次数
       ++modCount;
       //插入完成之后判断大小决定是否需要扩容
       if (++size > threshold)
           resize();
       afterNodeInsertion(evict);
       return null;
   }

其中有一个很值得注意的参数modCount。

 /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     */
    transient int modCount;

从注释可以看出这个参数是用于保存不同的将会影响到整个HashMap的结构的或者可能影响到其中元素大小的操作次数。用于在内部遍历方法中监控迭代过程中,被操作的情况。当在迭代器初始化完成获取到当时的modCount作为预期值之后,modCount在变脸过程中被改变,导致预期值与当前值不相等时会抛出异常 ConcurrentModificationException,之前在迭代器中遇到过这个问题。

上一篇下一篇

猜你喜欢

热点阅读