java基础(1.8)---HashMap源码分析(待完善)

一、HashMap简介

HashMap 是一个散列表,它存储的内容是键值对(key-value)映射。
HashMap 继承于AbstractMap,实现了Map、Cloneable、java.io.Serializable接口。

二、HashMap的主要构成

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 默认hashmap的大小(必须是2的幂次)
static final int MAXIMUM_CAPACITY = 1 << 30;//hashmap最大的大小
static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认的负载系数

transient Node<K,V>[] table; //数据的存储结构
transient Set<Map.Entry<K,V>> entrySet;
transient int size; //当前的大小(数量)
transient int modCount; //hashmap被更改的次数
int threshold;//这个参数是 大小*负载系数 
final float loadFactor;//负载系数

//数据在hashmap中保存的结构(1.6是Entity类,1.8是重新做了覆写)
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;
        }
    }

三、实际的使用

package jihemap.hashMap;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * map集合的实现方式一:HashMap (90%)
 * @author 76519
 *
 */
public class TestHashMap {
	public static void main(String[] args) {
		Map<Integer, String> map = new HashMap<Integer,String>();
		String a = map.put(1, "hello");
		System.out.println("a-->"+a);
		String b = map.put(2, "java");
		System.out.println("b-->"+b);
		String c = map.put(3, "world");
		System.out.println("c-->"+c);
		String d = map.put(3, "mldn");//重复的key
		System.out.println("d-->"+d);
		String e = map.put(4, "hello");//重复的value
		System.out.println("e-->"+e);
		
		//0.75的系数   默认数组的大小为16   16x0.75=12
		for (int i = 0; i < 16; i++) {
			map.put(i+4, "香蕉");
		}
		
		System.out.println(map);//运行发现   重复的key  会保存最后个key的信息
		System.out.println(map.get(3));
		
		System.out.println(map.get(9999));//null
		
		/**取得所有的key信息**/
		Set<Integer> keySet = map.keySet();
		Iterator<Integer> iterator = keySet.iterator();//集合输出   优先使用迭代器  Iterator
		while(iterator.hasNext()) {
			Integer key = iterator.next();
			System.out.println("key="+key+",value="+map.get(key));
		}
		
		/**
		 * hashMap原理:数据量小的时候,是按照链表的模式进行存储数据;
		 * 当存储量变大之后为了进行快速查找,那么会将这个链表变为一个红黑树(二叉树),用hash码作为数据的定位,来进行保存。
		 * 
		 */
	}
}

四、分段源码分析

1、hashmap的构造方法(三种)

①传入指定的hashmap大小和负载系数,构建hashmap对象

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  initialCapacity the initial capacity
     * @param  loadFactor      the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    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;
        this.threshold = tableSizeFor(initialCapacity);
    }

②传入大小,但使用默认的负载系数创建hashmap对象

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param  initialCapacity the initial capacity.
     * @throws IllegalArgumentException if the initial capacity is negative.
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

③无参构造(采取默认的大小和默认的负载系数)

    /**
     * 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、本次采取无参构造的方式创建hashmap对象

Map<Integer, String> map = new HashMap<Integer,String>();

源码是如何实现的?

上面的无参构造方法说的很清楚了,是将默认的大小(hashmap数据是table数组,至于table的类型则是Node<K,V>[],对!就是数组)和默认的负载系数。

这个负载系数是什么,等会再讲。

3、向hashmap集合中添加数据

String a = map.put(1, "hello");
System.out.println("a-->"+a);
String b = map.put(2, "java");
System.out.println("b-->"+b);
String c = map.put(3, "world");
System.out.println("c-->"+c);
String d = map.put(3, "mldn");//重复的key
System.out.println("d-->"+d);
String e = map.put(4, "hello");//重复的value
System.out.println("e-->"+e);

运行结果

a-->null
b-->null
c-->null
d-->world
e-->null

源码分析

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

    /** 
     * 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;
        //创建hashmap对象时,会加载他的属性,属性中有table项,不过是个null
        //此处是将table赋值给局部变量,并判断他的大小(由于在刚开始创建集合时,table就是null的)
        if ((tab = table) == null || (n = tab.length) == 0)
            //所以最开始的添加操作,会走此处,resize()做了什么呢?
            //最初为空时,会去计算阈值等信息
            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)
            //如果当前的大小大于阈值时,他会离散旧的hashmap集合,将大小翻一倍,将旧数据重新添加至新的集合中并返回
            resize();
        afterNodeInsertion(evict);
        return null;
    }

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;
        //当前node数组的大小
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        //当前能够存储的阈值---hashmap集合大小与负载系数的乘积
        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);
        }
        //如果此时的阈值计算为0
        if (newThr == 0) {
            //则采取默认的hashmap乘负载系数(可能是默认,可能是用户自定义)
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        //创建新的Node对象保存数据
        @SuppressWarnings({"rawtypes","unchecked"})
        Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        //判断当前的hashmap中的node数组是否存在(当存在时,会将旧的数据保存至新的数组中)
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                //Node数组中的每个数据都是Node对象,将每个Node对象赋值给局部的Node变量
                if ((e = oldTab[j]) != null) {
                    //如果单个的Node对象存在,将数据至空
                    oldTab[j] = null;
                    //如果Node的next属性(其实也是Node对象)是否为空----即是否存在下一个数据
                    if (e.next == null)
                        //如果没有下一个数据   则将此时的node对象信息保存至新的Node对象数组中
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        //如果此时的node对象类型是 TreeNode
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        //1、遍历数据时,如果判断存在下一个对象数据
                        //2、且对象的类型  不是  TreeNode
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        //取到Node数组中的最后一个Node对象
                        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;
    }

4、从集合中取得数据(根据key找到对应的Node对象并获取其value属性值)

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     * <p>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.)
     *
     * <p>A return value of {@code null} does not <i>necessarily</i>
     * 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;
    }

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

五、对几个参数的理解加强

debug测试,当采取默认的大小和负载系数时,在个数不超过 16*0.75=12的情况下的运行和超过12的运行

不超过时:

超过12时

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值