Java学习Day09 HashMap

Java学习Day09 HashMap

HashMap源码在这里插入图片描述

public class HashMapSource {
@SuppressWarnings({"all"})
    public static void main(String[] args) {
        //>扩容机制[和HashSet相同]
    //1) HashMap底层维护了Node类型的数组table,默认为null
    //2)当创建对象时,将加载因子(loadfactor)初始化为0.75.
    //3)当添加key-val时,通过key的哈希值得到在table的索引。然后判断该索引处是否有元素,如果没有元素直接添加。
    // 如果该索引处有元素,继续判断该元素的key是否和准备加入的key相等,如果相等,则直接替换val;
    // 如果不相等需要判断是树结构还是链表结构,做出相应处理。如果添加时发现容量不够,则需要扩容。
    //4)第1次添加,则需要扩容table容量为16,临界值(threshold)为12.
    //5)以后再扩容,则需要扩容table容量为原来的2倍,临界值为原来的2倍,即24,依次类推。6)在Java8中,如果一条链表的元素个数超过TREEIFY_THRESHOLD(默认是8),粗
    //table的大小>= MIN_TREEIFY_CAPACITY(默认64),就会进行树化(红黑树)
    //以下是源码解读
    HashMap hashMap = new HashMap();

//执行构造器       public HashMap() {
//初始化加载因子        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
//                  }这个时候HashMap的table=null
    hashMap.put("java",1);
    /*
    public V put(K key, V value) {key="java" value=1
        return putVal(hash(key), key, value, false, true);
    }
         static final int hash(Object key) {hash(key)调用的方法
        int h;                           无符号向右移16位
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    ====================================================================
    put方法本体
        final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;辅助变量
        if ((tab = table) == null || (n = tab.length) == 0)底层数组为空或数组长度为0
            n = (tab = resize()).length;新的数组直接扩容进入下面的resize方法
            进入resize之后就创建了一个全空的table表
        if ((p = tab[i = (n - 1) & hash]) == null)取出hash值对应的table的索引位置的Node判断当前位置是否为空
            tab[i] = newNode(hash, key, value, null);将Value值赋到table表里
        else {
            Node<K,V> e; K k;辅助变量
            if (p.hash == hash &&  1.hash值是否相同 2.key是否是同一个对象或者equals相同
                ((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 {链表 新的元素和链表中的每一个值比较有一个相同就break
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st 扩容的时候是8 11的时候树化当然删除到元素为6退化成链表
                            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;
    }
=====================================================================
扩容方法本体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) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;第一次新数组的扩容16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];这里是Node的table表扩容16
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
    * */
    hashMap.put("python",1);
    hashMap.put("java",2);
}
}

HashMap树化

public class HashMapTreeify {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap();
        for (int i = 1; i <=12 ; i++) {
            hashMap.put(new A(i),"hello");
        }
/*
    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        table为空或者长度小于64会扩容 否则树化 在一条链表上到达11个就树化
        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);树化整个table表
        }
    }



*/
    }
}
class A{
    private int num;

    public A(int num) {
        this.num = num;
    }

    @Override
    public int hashCode() {
        return 100;
    }

    @Override
    public String toString() {
        return "A{" +
                "num=" + num +
                '}';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值