HashMap(jdk8)源码

1、特点:

(1)HashMap是基于Hash表的,因此HashMap是无序的

(2)HashMap的键和值都允许为null

(3)HashMap不是线程安全的

2、先上JAVA的一个简单示例,然后根据例子分析源码

public static void main(String[] args) {
		// TODO Auto-generated method stub
      HashMap<String,String> hmap=new HashMap<>();
      hmap.put("8", "8");
      hmap.put("6", "6");
      hmap.put("10", "10");
      hmap.put("9", "9");
      Set<String> keySetStr=hmap.keySet();
      Iterator<String> iteKey=keySetStr.iterator();
      System.out.print("输出HashMap中的元素为:");
      while(iteKey.hasNext()) {
    	  System.out.print(hmap.get(iteKey.next())+" ");
      }
      System.out.println("");
      System.out.println(hmap.containsKey("2"));//false
      System.out.println(hmap.containsValue("6"));//true
	}

输出结果为:

输出HashMap中的元素为:6 8 9 10 
false
true

可见,定义的插入顺序与输出顺序是无关的。接下来根据源码分析过程

3、HashMap执行过程:

(1)定义HashMap。可以看到,执行没有参数的构造方法之后,只将加载因子设为默认加载因子为0.75.

/**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

(2)调用put方法向HashMap中插入值

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

可以看到,put方法的作用是在map中将Key和Value关联在一起。如果Map中已经包含这个Key所对应的映射,则将值进行替换。调用put方法后,会返回与该Key绑定的上一个Value值。若以往Map中不存在该Key对应的映射,则返回Null。可以看到,put(K key,V value)方法实际上调用的是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;//执行1
        if ((p = tab[i = (n - 1) & hash]) == null)//判断该key所对应的索引位置是否为null
            tab[i] = newNode(hash, key, value, null);//若为空则直接插入数组中
        else {//若不为null,则插入链表或红黑树中
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;//如果key重复,则进行替换
            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);//当元素个数大于8时,将链表转为红黑树
                        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;
    }

可以看到,在初始情况下,由于table==null,会调用resize()方法,也就是代码执行1处。resize()方法如下:

 /**
     * 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() {
        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;
            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的大小。当旧容量为0的时候,会将默认初始容量16作为新容量。否则,新容量就变为原容量的2倍,然后将oldTab中的数据一一插入到newTab中。然后继续看putVal方法(待续)。

(3)调用get方法获取key所对应的值

/**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     */
    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

可以看到调用get方法后,就会执行getNode(hash(key),key)方法获取该key所对应的node节点,获取到结点后,就会调用value方法获取对应值。getNode(hash,key)代码如下:

/**
     * 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) {//获取数组中在该索引位置的元素
            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;
    }

(4)KeySet方法是怎么执行的?

(5)containsKey方法

 /**
     * Returns <tt>true</tt> if this map contains a mapping for the
     * specified key.
     *
     * @param   key   The key whose presence in this map is to be tested
     * @return <tt>true</tt> if this map contains a mapping for the specified
     * key.
     */
    public boolean containsKey(Object key) {
        return getNode(hash(key), key) != null;
    }

该方法同样执行getNode方法,看返回值是否为null。

(6)containsValue方法

 /**
     * Returns <tt>true</tt> if this map maps one or more keys to the
     * specified value.
     *
     * @param value value whose presence in this map is to be tested
     * @return <tt>true</tt> if this map maps one or more keys to the
     *         specified value
     */
    public boolean containsValue(Object value) {
        Node<K,V>[] tab; V v;
        if ((tab = table) != null && size > 0) {
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next) {
                    if ((v = e.value) == value ||
                        (value != null && value.equals(v)))
                        return true;
                }
            }
        }
        return false;
    }

给该方法逐个遍历数组,再按链表遍历数组每个元素,判断是否具有相同值的,若是则为true,否则则为false.(该方法是否没考虑红黑树?)

(7)总结

在调用put方法向HashMap中添加元素的时候,若初始容量为0,会先将容量扩容为默认初始容量为16,然后当需要的容量查过旧容量*加载因子的时候,会将容量扩大为之前容量的2倍,然后将之前的元素逐个插入到新数组及数组对应的链表或红黑树中。在插入的时候,首先根据key值计算Hash,然后计算出该元素在数组中的索引位置,再判断该位置处是否为Null,若为空,则直接插入,若不为空,则判断是否为红黑树节点,若是,则插入红黑树中,否则插入到链表中,在插入之后,再判断链表长度是否大于8,若大于8,则将链表转为红黑树。

在调用get方法获取对应值的时候,首先获取key对应的hash,然后计算出该hash在数组中的索引位置,获取该位置元素。然后再比较元素的key是否真的相同,若相同则返回该元素。然后逐个对比链表或红黑树中的元素,直到找到对应元素。

 

欢迎指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值