HashMap原码阅读

JDK1.8 HashMap

文章目录

  • JDK1.8 HashMap
    • HashMap继承的类,和接口
    • HashMap的常量
    • 静态内部类Node
    • hash函数
    • comparableClassFor方法
    • tableSizeFor
    • 成员变量
      • table
      • entrySet
      • size
      • modCount
      • threshold
      • loadFactor
  • HashMap的4个初始化函数
  • putMapEntries
  • getNode函数
  • put函数
    • putVal
  • resize函数

HashMap继承的类,和接口

HashMao继承了AbstractMap类,实现了Map,Cloneable,Serializable接口。主要看探讨HashMap的实现。

HashMap的常量

默认初始化容量为1<<4。

 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

最大的容量大小

static final int MAXIMUM_CAPACITY = 1 << 30;

默认的装载因子0.75,当当前容量大小size大于当前总容量*DEFAULT_LOAD_FACTOR 就会扩容

static final float DEFAULT_LOAD_FACTOR = 0.75f;

默认当链表长度大于8时转变成红黑树维护.
红黑树原理
代码实现

static final int TREEIFY_THRESHOLD = 8;

默认树转链表的阈值:

static final int UNTREEIFY_THRESHOLD = 6;

默认table中至少包含64个键值对才转化成树

static final int MIN_TREEIFY_CAPACITY = 64;

静态内部类Node

实现了Map.Entry接口

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;   //hash被申明为final
        final K key;      //key也被申明为final
        V value;		  //value不是final
        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; }    //被申明为final
        public final V getValue()      { return value; }  //被申明为final
        public final String toString() { return key + "=" + value; } //被申明为final

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);   //重写hashCode方法
        }

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

        public final boolean equals(Object o) {    //重写equals方法
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {              //必须要实现Map.Entry接口才能比较,并且key和value值都相等才能比较
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

hash函数

hash函数是一个static final修饰的函数,静态的,不可修改。
从源代码来看hashmap允许值为空。

 static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);  
        //如果key == null 那么返回0 否则返回(h = key.hashCode() )^(h >>>16 )
        //充分利用了key.hashCode()的高16位,增加key.hashCode 低16位的随机性。 
    }

comparableClassFor方法

先来看看他的注释

/**
     * Returns x's Class if it is of the form "class C implements
     * Comparable", else null.
     */

如果他是这种形式class C implements Comparable 那么就返回x的Class对象。

那么这个函数的具体作用是干什么的呢?
当链表中的数量大于8时那么他会转化成一个棵红黑树,当put一个新元素时,如果该元素键的hash值小于当前节点的hash值的时候,就会作为当前节点的左节点;hash值大于当前节点hash值得时候作为当前节点的右节点。那么hash值相同的时候呢?这时还是会先尝试看是否能够通过Comparable进行比较一下两个对象(当前节点的键对象和新元素的键对象),要想看看是否能基于Comparable进行比较的话,首先要看该元素键是否实现了Comparable接口,此时就需要用到comparableClassFor方法来获取该元素键的Class,然后再通过compareComparables方法来比较两个对象的大小。

static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() ==
                         Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }

/**
* 如果x所属的类是kc,返回k.compareTo(x)的比较结果
* 如果x为空,或者其所属的类不是kc,返回0
*/
@SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
static int compareComparables(Class<?> kc, Object k, Object x) {
    return (x == null || x.getClass() != kc ? 0 :
            ((Comparable)k).compareTo(x));
}

tableSizeFor

static final int tableSizeFor(int cap) 当创建一个新的hashmap的时候带了cap参数,这个时候这个函数用来寻找大于它且离他最近的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;
    	//如果n = 0,结果这些操作之后应该返回1
    }
    

成员变量

table

/**
     * 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;

entrySet

/**
     * Holds cached entrySet(). Note that AbstractMap fields are used
     * for keySet() and values().
     */
transient Set<Map.Entry<K,V>> entrySet;

size

/**
     * The number of key-value mappings contained in this map.
     */
    transient int size;

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;

threshold

/**
     * The next size value at which to resize (capacity * load factor).
     *
     * @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;

loadFactor

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

HashMap的4个初始化函数

带初始化的容量和装载因子

public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity); //如果初始化容量<0则抛出异常
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);   //如果装载因子小于0或者是一个非数字则跑出异常
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);   //获取大于且离他最近的2次幂
    }

这个就简单了

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

默认的这里只设置了loadFactor。估计capacity在具体初始话的时候设置

/**
     * Constructs an empty HashMap with the default initial capacity
     * (16) and the default load factor (0.75).
     */
public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }
//构造一个映射关系与指定 Map 相同的新 HashMap。 
public HashMap(Map<? extends K, ? extends V> m) {    //
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);   //主要通过这个函数去构造
    }

putMapEntries

/** 
     * Implements Map.putAll and Map constructor
     *
     * @param m the map
     * @param evict false when initially constructing this map, else
     * true (relayed to method afterNodeInsertion).
     */
    final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();   //获取传入map的大小,如果为null则抛出异常
        if (s > 0) {
            if (table == null) { // pre-size    table还没初始化
                float ft = ((float)s / loadFactor) + 1.0F;      
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);  //计算阈值
            }
            else if (s > threshold)   //如果已经table已经初始化了并且s>阈值那么就需要扩容
                resize();
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {  
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }
/**
     * Returns the number of key-value mappings in this map.
     *
     * @return the number of key-value mappings in this map
     */
    public int size() {
        return size;
    }

    /**
     * Returns true if this map contains no key-value mappings.
     *
     * @return true if this map contains no key-value mappings
     */
    public boolean isEmpty() {
        return size == 0;
    }
/**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * 

More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * *

A return value of {@code null} does not necessarily * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * * @see #put(Object, Object) */ public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; //如果getNode返回的值为null就直接返回空否则返回e.value }

getNode函数

//代码很简介,易懂,先把要用的变量全部声明好。

/**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
 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) {
            //如果tab已经初始化了 并且长度大于0 并且first不为空
            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)  //在判断是不是treeNode treeNode和Node感觉有继承关系
                    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;
    }

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 key, or
     *         null if there was no mapping for key.
     *         (A null return can also indicate that the map
     *         previously associated null with key.)
     */
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

putVal

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

resize函数

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;     
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;  //threshold如果当前size大于这个就扩容
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {   //如果oldCup大于MAXIMUM_CAPACITY的最大容量了
                threshold = Integer.MAX_VALUE; //那么把threshold变成max的最大值
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold、
                //如果newCap = oldCap的两倍 并且小于最大的容量 并且大于初始的容量    阈值变为两倍
        }
        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"})
            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;
                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原码阅读)