HashMap的源码解析

特点:数据存储方式为散链表(数组+链表或数组+红黑树)

初始化

HashMap有四种初始化方式:
方式一:

public HashMap() {
	this.loadFactor = DEFAULT_LOAD_FACTOR; 
}

方式二:

public HashMap(int initialCapacity) {	//initialCapacity是长度
	this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

方式三:

public HashMap(int initialCapacity, float loadFactor) {
	if (initialCapacity < 0)	//判断initialCapacity的值是否正常
		throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
	if (initialCapacity > MAXIMUM_CAPACITY) //判断initialCapacity的值是否超过设置的最大容量
		initialCapacity = MAXIMUM_CAPACITY;	//如果超过则为最大容量
	if (loadFactor <= 0 || Float.isNaN(loadFactor))	//判断loadFactor的值是否正常
		throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
	this.loadFactor = loadFactor;
	this.threshold = tableSizeFor(initialCapacity);	//初始化容量
}
/**
*  返回最接近cap的2的n次幂,目的:为了减少hash冲突
* 例:8
* 8 换成二进制 0000 1000 运算后 0000 1111 =15 ,返回15+1=16
* 总结:先将cap的值转换成二进制,将从最高位的1开始一直到最低位都化成1(如:0011 0101=>0011 1111,0100 *1000=>0111 1111),在将此数值+1不超过最大容量则返回
*/
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;
    }

方式四:

public HashMap(Map<? extends K, ? extends V> m) {
	this.loadFactor = DEFAULT_LOAD_FACTOR;
	putMapEntries(m, false);
}

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
	int s = m.size();
	if (s > 0) {
		if (table == null) { // pre-size
			float ft = ((float)s / loadFactor) + 1.0F;
			int t = ((ft < (float)MAXIMUM_CAPACITY) ?
					(int)ft : MAXIMUM_CAPACITY);
			if (t > threshold)
				threshold = tableSizeFor(t);//同上
		}
		//以上判断map是否正常
		else if (s > threshold)	//判断是否超过当前容量,超过则扩容
			resize();	//见扩容标题
		//	遍历输入的map,每一个都put进去
		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);	//见put标题
		}
	}
}

get

/**
* 计算hash值
*/
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);//防止hash值冲突过高
}

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) {	//判断这个hash在散链表的数组中是否存在
        if (first.hash == hash && // always check first node	
            ((k = first.key) == key || (key != null && key.equals(k))))	//判断找到的key是否是理想值,不是理想值说明hash冲突
            return first;
        if ((e = first.next) != null) {	//判断是否存在下一个节点,如果为空证明查找的key不存在
            if (first instanceof TreeNode)	//判断冲突的hash是不是按树结构来存储
                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;
}

remove

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}

final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
   //找
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {	//拿到key的节点
        Node<K,V> node = null, e; K k; V v;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))	//判断是不是要找的值
            node = p;
        //不是按照树或链表的结构来查找
        else if ((e = p.next) != null) {	
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
       //删,按链表或树结构删除,不能使其断链
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;		//返回删除的节点
        }
    }
    return null;	//没有要删的节点,返回null
}

put

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

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)//如果是第一次put进行扩容
        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;
        //判断插入的key是否等于当前的key
        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;
            //如果value不相等才进行赋值
            if (!onlyIfAbsent || oldValue == null)	
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    //如果当前长度大于预值进行扩容(默认预值=0.75*当前容量)
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

resize

/**
 * 扩容目的:减少hash冲突
 * 如果节点的hash小于老容量,在数组中的位置不变
 * 节点的hash与新容量进行与运算,如果最高位是1则在数组新位置上,如果最高位是0则还在数组原位置上
 * 过程:遍历老数组,找到冲突的链表或树,遍历节点,判断位置是否在新位置,如果在,原索引+原数组长度=新索引
 */
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;
}
posted @ 2022-03-07 18:04  叕叕666  阅读(42)  评论(0)    收藏  举报