zoukankan      html  css  js  c++  java
  • HashMap结构及使用

    HashMap的数据结构

    HashMap主要是用数组来存储数据的,我们都知道它会对key进行哈希运算,哈系运算会有重复的哈希值,对于哈希值的冲突,HashMap采用链表来解决的。在HashMap里有这样的一句属性声明:

    transient Entry[] table;

    Entry就是HashMap存储数据所用的类,它拥有的属性如下

    final K key;
    V value;
    final int hash;
    Entry<K,V> next;

    看到next了吗?next就是为了哈希冲突而存在的。比如通过哈希运算,一个新元素应该在数组的第10个位置,但是第10个位置已经有Entry,那么好吧,将新加的元素也放到第10个位置,将第10个位置的原有Entry赋值给当前新加的 Entry的next属性。数组存储的是链表,链表是为了解决哈希冲突的,这一点要注意。

    几个关键的属性
    存储数据的数组

    transient Entry[] table; 这个上面已经讲到了
    默认容量
    static final int DEFAULT_INITIAL_CAPACITY = 16;
    最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;

    默认加载因子,加载因子是一个比例,当HashMap的数据大小>=容量*加载因子时,HashMap会将容量扩容

    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    当实际数据大小超过threshold时,HashMap会将容量扩容,threshold=容量*加载因子

    int threshold;

    加载因子

    final float loadFactor;

    HashMap的初始过程
    构造函数1

    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
      int capacity = 1;
      while (capacity < initialCapacity)
        capacity <<= 1;
    
      this.loadFactor = loadFactor;
      threshold = (int)(capacity * loadFactor);
      table = new Entry[capacity];
      init();
    }

    重点注意这里

    while (capacity < initialCapacity)
      capacity <<= 1;

    capacity才是初始容量,而不是initialCapacity,这个要特别注意,如果执行new HashMap(9,0.75);那么HashMap的初始容量是16,而不是9,想想为什么吧。

    构造函数2

    public HashMap(int initialCapacity) {
       this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    构造函数3,全部都是默认值

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
        table = new Entry[DEFAULT_INITIAL_CAPACITY];
        init();
    }

    构造函数4

    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);
    }

    如何哈希
    HashMap并不是直接将对象的hashcode作为哈希值的,而是要把key的hashcode作一些运算以得到最终的哈希值,并且得到的哈希值也不是在数组中的位置哦,无论是get还是put还是别的方法,计算哈希值都是这一句:

    int hash = hash(key.hashCode());

    hash函数如下:

    static int hash(int h) {
        return useNewHash ? newHash(h) : oldHash(h);
    }

    useNewHash声明如下:

    private static final boolean useNewHash;
    static { useNewHash = false; }

    这说明useNewHash其实一直为false且不可改变的,hash函数里对 useNewHash的判断真是多余的。

    private static int oldHash(int h) {
        h += ~(h << 9);
        h ^= (h >>> 14);
        h += (h << 4);
        h ^= (h >>> 10);
        return h;
    }
    
    private static int newHash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

    其实HashMap的哈希函数会一直都是oldHash。


    如果确定数据的位置
    看下面两行

    int hash = hash(k.hashCode());
    int i = indexFor(hash, table.length);

    第一行,上面讲过了,是得到哈希值,第二行,则是根据哈希指计算元素在数组中的位置了,位置的计算是将哈希值和数组长度按位与运算。

    static int indexFor(int h, int length) {
      return h & (length-1);
    }

    put方法到底作了什么?

    public V put(K key, V value) {
      if (key == null)
        return putForNullKey(value);
      int hash = hash(key.hashCode());
      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;
    }

     如果key为NULL,则是单独处理的,看看putForNullKey方法:

    private V putForNullKey(V value) {
        int hash = hash(NULL_KEY.hashCode());
        int i = indexFor(hash, table.length);
    
      for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        if (e.key == NULL_KEY) {
          V oldValue = e.value;
          e.value = value;
          e.recordAccess(this);
          return oldValue;
        }
      }
    
      modCount++;
      addEntry(hash, (K) NULL_KEY, value, i);
      return null;
    }    

     NULL_KEY的声明:

    static final Object NULL_KEY = new Object();

    这一段代码是处理哈希冲突的,就是说,在数组某个位置的对象可能并不是唯一的,它是一个链表结构,根据哈希值找到链表后,还要对链表遍历,找出key相等的对象,替换它,并且返回旧的值。

    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
      if (e.key == NULL_KEY) {
        V oldValue = e.value;
        e.value = value;
        e.recordAccess(this);
        return oldValue;
      }
    }

     如果遍历完了该位置的链表都没有找到有key相等的,那么将当前对象增加到链表里面去

    modCount++;
    addEntry(hash, (K) NULL_KEY, value, i);
    return null;

    且看看addEntry方法

    void addEntry(int hash, K key, V value, int bucketIndex) {
      Entry<K,V> e = table[bucketIndex];
      table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
      if (size++ >= threshold)
        resize(2 * table.length);
      }
      table[bucketIndex] = new Entry<K,V>(hash, key, value, e);新建一个Entry对象,并放在当前位置的Entry链表的头部,看看下面的 Entry构造函数就知道了,注意红色部分。
      Entry(int h, K k, V v, Entry<K,V> n) {
      value = v;
      next = n;
      key = k;
      hash = h;
    }

    如何扩容?

    当put一个元素时,如果达到了容量限制,HashMap就会扩容,新的容量永远是原来的2倍。
    上面的put方法里有这样的一段:

    if (size++ >= threshold)
    resize(2 * table.length);

    这是扩容判断,要注意,并不是数据尺寸达到HashMap的最大容量时才扩容,而是达到 threshold指定的值时就开始扩容, threshold=最大容量*加载因子。 看看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);
      table = newTable;
      threshold = (int)(newCapacity * loadFactor);
    }

     重点看看红色部分的 transfer方法

    void transfer(Entry[] newTable) {
      Entry[] src = table;
      int newCapacity = newTable.length;
      for (int j = 0; j < src.length; j++) {
        Entry<K,V> e = src[j];
        if (e != null) {
          src[j] = null;
          do {
            Entry<K,V> next = e.next;
            int i = indexFor(e.hash, newCapacity); 
            e.next = newTable[i];
            newTable[i] = e;
            e = next;
          } while (e != null);
        }
      }
    }

    tranfer方法将所有的元素重新哈希,因为新的容量变大,所以每个元素的哈希值和位置都是不一样的。



    正确的使用HashMap
    1:不要在并发场景中使用HashMap
    HashMap是线程不安全的,如果被多个线程共享的操作,将会引发不可预知的问题,据sun的说法,在扩容时,会引起链表的闭环,在get元素时,就会无限循环,后果是cpu 100%。
    看看get方法的红色部分

    public V get(Object key) {
      if (key == null)
        return getForNullKey();
      int hash = hash(key.hashCode());
      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.equals(k)))
          return e.value;
      }
      return null;
    }

    2:如果数据大小是固定的,那么最好给HashMap设定一个合理的容量值

    根据上面的分析,HashMap的初始默认容量是16,默认加载因子是0.75,也就是说,如果采用HashMap的默认构造函数,当增加数据时,数据实际容量超过16*0.75=12时,HashMap就扩容,扩容带来一系列的运算,新建一个是原来容量2倍的数组,对原有元素全部重新哈希,如果你的数据有几千几万个,而用默认的HashMap构造函数,那结果是非常悲剧的,因为HashMap不断扩容,不断哈希,在使用HashMap的场景里,不会是多个线程共享一个HashMap,除非对HashMap包装并同步,由此产生的内存开销和cpu开销在某些情况下可能是致命的。

    转自:http://www.java3z.com/cwbwebhome/article/article8/81388.html?id=3973

  • 相关阅读:
    链表中环的入口节点
    链表中倒数第k个节点
    调整数组顺序使奇数位于偶数前面
    53. Maximum Subarray
    42. Trapping Rain Water
    48. Rotate Image
    css技巧一
    html语义
    label标签表单响应
    CSS清除浮动
  • 原文地址:https://www.cnblogs.com/olmlo/p/4775459.html
Copyright © 2011-2022 走看看