浅谈hashMap jdk1.7与1.8

1. 底层实现
    jdk1.7: 数组+链表
    jdk1.8: 数组+链表+红黑树

2. 存放对象
     jdk1.7存放的是Entry对象

 static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        final int hash;

        /**
         * Creates new entry.
         */
        Entry(int h, K k, V v, Entry<K,V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }

        public final K getKey() {
            return key;
        }

        public final V getValue() {
            return value;
        }

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

        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }

        public final int hashCode() {
            return (key==null   ? 0 : key.hashCode()) ^
                   (value==null ? 0 : value.hashCode());
        }

        public final String toString() {
            return getKey() + "=" + getValue();
        }

        /**
         * This method is invoked whenever the value in an entry is
         * overwritten by an invocation of put(k,v) for a key k that's already
         * in the HashMap.
         */
        void recordAccess(HashMap<K,V> m) {
        }

        /**
         * This method is invoked whenever the entry is
         * removed from the table.
         */
        void recordRemoval(HashMap<K,V> m) {
        }
    }

     jdk1.8存放的是Node对象

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

3. 链表插入法

    hashmap的链表的作用都是为了解决hash冲突,但是如果发生了hash冲突(也就是计算出来的存放在数组的index一样),该如何将Entry/Node插入链表中?

    jdk1.7采用的是头插法并且插入后将新添加的对象移动到数组上
    头插法的优势:插入的效率更快,因为不需要遍历原有的链表,直接进行插入即可!
    为什么要移动对象:不移动的话遍历链表的时候无法遍历到新添加的数据

    jdk1.8采用的是尾插法
    尾插法能解决头插法存在的一些问题

4. 构造方法
    jdk1.7

 public HashMap() {
    this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}

//initialCapacity 默认值为16, loadFactory默认为0.75f
 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();
}

    jdk1.8

   public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

5. 为什么能快速获取hashMash的长度
    因为维护了一个size属性,在进行put操作时,size++

6. 如何进行扩容的?
    当实际容量达到 容量*加载因子的个数时,就会进行扩容,扩容的规律:每次扩容都会乘以2;注意点:就算我们调用hashMap的有参数构造方法(也就是调用指定初始容量的构造方法),hashMap也是不一定就是初始化容量为你指定的容量,他会给你初始化一个比你指定的数要大的满足2的n次方的数,例如,你指定的容量为5,那hashmap会初始化容量为8;若指定的容量为10,hashmap会初始化容量为16;

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

7. 为什么hashmap的数组长度一定要是2的n次方?
    

    /**
     * Returns index for hash code h.
     */
     //h代表的时hashcode,length代表的是数组的长度
    static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1);
    }

    在放入entry/node对象时,需要确定其放入的数组的下标,上面的 & 操作在什么情况下能计算出不超出数组长度的index呢?
    举个例子:
    h的二进制为:01010101,数组的长度为16(满足2的n次方),16的二进制为:00010000,那么length-1为15,15的二进制为:00001111;h & (length-1)为:
        0101 0101
    &  0000 1111
     ------------------         &操作同为1才是1,其他为0;
        0000 0101
    0101转为十进制为5,满足在 0到length-1 的范围
    如果不是2的n次方,那结果就可能数组越界或者一直放在数组的一两个位置, 分布不均匀了。

7. 为什么采用&操作而不采用取余进行数组位置的计算呢?
    &操作计算速度更快!

8. 为什么进行hsah的时候,会进行右移以及异或运算?

    final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }

        h ^= k.hashCode();

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

    一个int的hash值是占32位的,但是在第6点确定数组位置的时候,我们知道如果数组的长度为16,那么&运算时,只有最低几位会参与到运算,那么高位就不起作用了;所以,在进行hash计算的时候,就会进行一系列的右移以及异或操作,让高位也参与运算中去;这样可以更加均匀分布在数组上以及保证各个链表长度基本一致

9. 扩容
    jdk1.7是先执行扩容再进行插入
    jdk1.8是先执行插入再进行扩容
    扩容的时候有规律的,在新数组的位置要不是原来位置,要不就是原来的位置加上就数组长度的位置;jdk1.7没有运用这个规律,jdk1.8就有运用到这个规律。
    jdk1.8设置多了两个阈值

 /**
     * 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.
     */
    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.
     */
    static final int UNTREEIFY_THRESHOLD = 6;

    这就是在链表的长度大于8的时候,有可能会变为红黑树,但是不一定,如果链表的长度大于8但是数组的长度小于64,此时不会变为红黑树,而是先进行数组的扩容,这样基本能将链表的长度缩短。
    在红黑树的节点个数小于等于6的时候,会将红黑树转为链表。为什么不是都设为8呢?为了避免频繁进行链表与红黑树的转换(会降低性能效率)

    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        //MIN_TREEIFY_CAPACITY = 64;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();// 扩容
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;// 树化
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值