• HashMap源码分析


      本次分析使用的代码为JDK1.8中的HashMap代码。
      HashMap可以接受为null的key和value。
      由于HashMap中的方法没有加锁,所以HashMap不是线程安全的。

    Node类

    介绍

    • Node类为HashMap中的一个静态内部类,实现了Map.Entry接口。

    基本属性

    • 与HashTable中的Entry类属性一样,该类中也有hash、key、value、next四个字段。
      • hash:存储该Node的hash值。
      • key:存储键值。
      • value:存储值。
      • next:存储Node链表上的下一个结点。
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
    

    构造函数

    • 构造函数与HashTable中Entry的构造函数类似,为四个属性字段进行赋值。
    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }
    

    方法

    • Node中有getKey()、getValue()、setValue(V newValue)三个操作key和value的方法。
    • 重写了hashCode()和equals(Object o)方法。
      • hashCode()方法将key的hashCode和value的hashCode进行了异或运算。
      • equals方法需要判断key和value同时相同才会返回true,而且对象需要是实现了Map.Entry接口的类。
    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }
    
    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;
    }
    

    HashMap类

    基本属性

    • DEFAULT_INITIAL_CAPACITY的值为16,代表默认的HashMap中table的大小为16。
    • MAXIMUM_CAPACITY:2^30,最大容量值。
    • DEFAULT_LOAD_FACTOR:默认负载因子大小,为0.75.
    • TREEIFY_THRESHOLD:转换为树的临界值,当HashMap中链表的长度超过这个值时,就会自动转换为红黑树。
    • table:存储HashMap中Node的数组,也就是桶的数组。
    • size:键值对的数目。
    • threshold:临界值,默认初始化后为容量与负载因子的乘积。
    • loadFactor:负载因子。
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    
    static final int MAXIMUM_CAPACITY = 1 << 30;
    
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
    static final int TREEIFY_THRESHOLD = 8;
    
    transient Node<K,V>[] table;
    
    transient Set<Map.Entry<K,V>> entrySet;
    
    transient int size;
    
    int threshold;
    
    final float loadFactor;
    

    方法

    hash()方法

    • HashMap中的hash方法,若key为null,则返回0,否则返回的key的hash值与其向右无符号移16位的值的异或值。
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    

    put(K key, V value)方法

    • put方法调用了putVal方法。
    • putVal方法中有五个参数,分为为key的hash值,key,value,以及onlyIfAbsent和evict。当onlyIfAbsent为true时,不修改已经存在的value,当evict为false时,这个table在创建模式。
    • 第一个if语句判断table是否进行了初始化,若没有进行初始化,则调用resize()方法进行初始化,将容量和负载因子都赋值为默认值。
    • 接着取下标为(n - 1) & hash的table值,若为null,则代表是第一个,赋值为一个新的Node。
    • 若下标为(n - 1) & hash的table值不为null,则判断key是否与该结点的key相同,如果相同,则保存当前结点到一个临时结点e。
    • 如果上述都为false,则接着判断第一个结点是不是TreeNode,若为TreeNode,则调用putTreeVal方法。
    • 若上述都为false,则对该链表进行遍历,找寻key相同的Node,如果没有则在链表尾部新增一个Node,并判断链表长度是否超过8,若超过了8,则将链表转化为红黑树。若找到key相同的结点,则将旧值进行替换并返回旧值。
    • 若是在上一步新增了结点,则将size加1,并判断是否超过临界值,若超过则进行加倍扩容。
    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;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        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);
                        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;
    }
    

    get(Object key)方法

    • 当该key结点不存在时,返回null,否则调用getNode方法。
    • 如果该key所在结点为链表的头结点,那么就直接返回头结点。
    • 如果不是头结点,那么遍历这个链表,首先判断结点是否为红黑树结点,若是,则调用getTreeNode方法,查看该key值的红黑树结点。
      若不是红黑树结点则遍历链表,直到找到这个结点或者遍历完毕,找到则返回该结点,否则返回null。
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }
    

    resize()

    本方法用来初始化table或者将table的容量扩大一倍。

    /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    final Node<K,V>[] resize() {
    	// 保存旧的hashtable
        Node<K,V>[] oldTab = table;
    	// 获取hashtable的长度和门限值
        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;
            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"})
    		// 初始化新的table数组
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
    			// 若oldTab头结点不为空
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
    				// 若只有一个头结点,后面没有链表,则直接将久的头结点赋值给新的table上
                    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;
    						// 使用e.hash & oldCap,将链表结点分为lo和hi两类
                            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);
    					// 第一类lo结点置于新的table的原先相同的位置
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
    					// 第二类hi结点置于新的table的原来位置加oldCap的位置
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }
    

    TreeNode类

    介绍

    • HashMap类中的一个静态内部类,当链表结点数大于8时,将链表转化为红黑树,这个类就是红黑树的结点类。
    • 继承自LinkedHashMap.Entry<K,V>类,而LinkedHashMap.Entry<K,V>类继承自HashMap.Node<K,V>类,所以说其实TreeNode类是上述Node类的子类。
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V>
    
    static class Entry<K,V> extends HashMap.Node<K,V>
    
  • 相关阅读:
    acm入门 杭电1001题 有关溢出的考虑
    面向对象课后深入学习(C++ 类的静态成员详细讲解)
    Eclipse中导入项目后js报错解决方法
    mysql用户链接数
    配置服务器nginx 教程
    eclipse如何新建项目发布到git
    获取当天开始时间结束时间
    pdf在线加载·
    springmvc配置详解 教程
    hibulder中使用git教程
  • 原文地址:https://www.cnblogs.com/liuyang0/p/6434431.html
Copyright © 2020-2023  润新知