jdk 1.7 hashMap源码解读

hashMap概述

基于哈希表的 Map 接口的实现。此实现提供所有可选的映射操作,并允许使用 null 值和 null 键。(除了非同步和允许使用 null 之外,HashMap 类与Hashtable 大致相同。)此类不保证映射的顺序,特别是它不保证该顺序恒久不变

hashMap数据结构

hashMap结构是一个一维数组,数组里又有一个单向的列表,它们存储的都是Entry<K,V>,Entry中有一个属性有一个next指向下一个实体


类图结构


构建函数

推荐使用带初始容量的构造函数,防止使用默认初始容量,当数据量大时不停的扩容,重新排序消耗性能。

HashMap()
          构造一个具有默认初始容量 (16) 和默认加载因子 (0.75) 的空 HashMap
HashMap(int initialCapacity)
          构造一个带指定初始容量和默认加载因子 (0.75) 的空 HashMap(推荐使用)
HashMap(int initialCapacity, float loadFactor)
          构造一个带指定初始容量和加载因子的空 HashMap
HashMap(Map<? extendsK,? extendsV> m)
          构造一个映射关系与指定 Map 相同的新 HashMap

属性

/**
	 * The default initial capacity - MUST be a power of two. 默认初始值容量
	 */
	static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
	/**
	 * The maximum capacity, used if a higher value is implicitly specified by
	 * either of the constructors with arguments. MUST be a power of two <=
	 * 1<<30. 最大容量
	 */
	static final int MAXIMUM_CAPACITY = 1 << 30;
	/**
	 * The load factor used when none specified in constructor. 默认加载因子
	 */
	static final float DEFAULT_LOAD_FACTOR = 0.75f;
	/**
	 * An empty table instance to share when the table is not inflated.
	 * 表格未被填充前的空对象
	 */
	static final HashMap.Entry<?, ?>[] EMPTY_TABLE = {};
	/**
	 * The table, resized as necessary. Length MUST Always be a power of two.
	 * 大小改变是不可避免的,长度总是2的幂
	 */
	transient HashMap.Entry<K, V>[] table = (HashMap.Entry<K, V>[]) EMPTY_TABLE;
	/**
	 * The number of key-value mappings contained in this map. 大小
	 */
	transient int size;
	/**
	 * The next size value at which to resize (capacity * load factor).
	 * 临界值=capacity * load factor,当size大于=临界值时,有可能会扩容
	 */
	// If table == EMPTY_TABLE then this is the initial capacity at which the
	// table will be created when inflated.
	int threshold;
	/**
	 * The load factor for the hash table. 加载因子
	 */
	final float loadFactor;
	/**
	 * 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).
	 * 用于快速替代失败使用,当数据put,remove,等变更时modCount++,根据之前的值比较如果不相等抛ConcurrentModificationException
	 */
	transient int modCount;

样例、图片演示

package com.util;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangyl
 * @description
 * @date 2017/10/30
 * @see
 */
public class HashMapTest {

    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>(3);
        map.put("11","11");
        map.put("12","11");
        map.put("13","11");
        map.put("14","11");
        map.put("15","11");
        map.put("19","11");
    }
}

即使你传入参容量是3,它会根据取3-1<<1得到4,再取4二进制的取高位4为长度,数据的长度2的次方或2的次幂,1,2,4,8,16,32,

看下面四图,了解数据的hashMap数据的填充



第5个元素插入,当数据长度大于了他的临界值(threshold)

1、hashMap里的table会扩容

2、数据重新排序

3、有可能重新生成hashcode值

扩容重新排序




通过hascode &或最余(根据JDK不同)得到的下标并将值保存至下标对应的数据,将对应的next保存之前下标的数据


方法解读

hash

hash用于计算key值,具体原理自己理解
/**
     * Retrieve object hash code and applies a supplemental hash function to the
     * result hash, which defends against poor quality hash functions.  This is
     * critical because HashMap uses power-of-two length hash tables, that
     * otherwise encounter collisions for hashCodes that do not differ
     * in lower bits. Note: Null keys always map to hash 0, thus index 0.
     */
    final int hash(Object k) {
        int h = hashSeed;
        if (0 != h && k instanceof String) {
            return sun.misc.Hashing.stringHash32((String) k);
        }

        h ^= k.hashCode();

        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }

indexFor

根据hashCode值与table数组的长度取hashCode对应的下标,跟h%(lengt-1)得到下标结果是一样的
/**
     * Returns index for hash code h.
     */
    static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1);
    }

get

分别有两个方法,key==null和!=null,为null的数据被保存在index=0的数组里
1、得到hashCode
2、得到hashCode对应的数组index
3、通过Entry next迭代Entry,比较hashcode,key是否相等,相等返回value
public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }

    /**
     * Offloaded version of get() to look up null keys.  Null keys map
     * to index 0.  This null case is split out into separate methods
     * for the sake of performance in the two most commonly used
     * operations (get and put), but incorporated with conditionals in
     * others.
     */
    private V getForNullKey() {
        if (size == 0) {
            return null;
        }
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }
    final Entry<K,V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }

        int hash = (key == null) ? 0 : hash(key);
        for (Entry<K,V> e = table[indexFor(hash, table.length)];
             e != null;
             e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

put

1、初始化填充值(第一次)
2、得到hashCde
3、通过hashCode得到数组下标
4、找到下标对应的entry,如果key存在则替换并返回
5、key不存在进入addEntry方法
6、判断当前大小是否超过临界值,超时就扩容,重新生成hasCode(根据条件),所有数据重新排序组合( 性能消耗大
7、添加数据到对应的列表

因为插入是无序的,所以此类不保证映射的顺序
/**
	 * 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) {
		if (table == EMPTY_TABLE) {
			inflateTable(threshold);
		}
		if (key == null)
			return putForNullKey(value);
		int hash = hash(key);
		int i = indexFor(hash, table.length);
		for (Entry<K, V> e = table[i]; e != null; e = e.next) {
			Object k;
			if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
				V oldValue = e.value;
				e.value = value;
				e.recordAccess(this);
				//如果key存在,更新值并返回旧值
				return oldValue;
			}
		}
		modCount++;
		addEntry(hash, key, value, i);
		return null;
	}

	/**
	 * Inflates the table. 第一次put值时,初始化对象,填充值
	 */
	private void inflateTable(int toSize) {
		// Find a power of 2 >= toSize
		// 2的幂,取toSize二进制的最高位,比如3二进制为11
		int capacity = roundUpToPowerOf2(toSize);
		threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
		table = new Entry[capacity];
		initHashSeedAsNeeded(capacity);
	}

	/**
	 * 取2的幂 如果number==3,3-1<<1的最高位就是4,返回值就是4
	 */
	private static int roundUpToPowerOf2(int number) {
		// assert number >= 0 : "number must be non-negative";
		return number >= MAXIMUM_CAPACITY ? MAXIMUM_CAPACITY
				: (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
	}

	/**
	 * Adds a new entry with the specified key, value and hash code to the
	 * specified bucket. It is the responsibility of this method to resize the
	 * table if appropriate. Subclass overrides this to alter the behavior of
	 * put method.
	 */
	void addEntry(int hash, K key, V value, int bucketIndex) {
		// 当大小大于等于临界值时并table[bucketIndex]不为空时,扩容,size*2,size还是2的幂
		if ((size >= threshold) && (null != table[bucketIndex])) {
			resize(2 * table.length);
			hash = (null != key) ? hash(key) : 0;
			bucketIndex = indexFor(hash, table.length);
		}
		createEntry(hash, key, value, bucketIndex);
	}

	/**
	 * Like addEntry except that this version is used when creating entries as
	 * part of Map construction or "pseudo-construction" (cloning,
	 * deserialization). This version needn't worry about resizing the table.
	 * Subclass overrides this to alter the behavior of HashMap(Map), clone, and
	 * readObject.
	 */
	void createEntry(int hash, K key, V value, int bucketIndex) {
		// 将插入的数据放在最前面,并将自己的next指向之前下标的数据
		Entry<K, V> e = table[bucketIndex];
		table[bucketIndex] = new Entry<>(hash, key, value, e);
		size++;
	}

	/**
	 * Creates new entry.
	 */
	Entry(int h, K k, V v, HashMap.Entry<K,V> n) {
		value = v;
		next = n;
		key = k;
		hash = h;
	}

remove

1、得到hashCde
2、通过hashCode得到数组下标
3、移除并返回key对应的值,如果找不到返回null
/**
	 * Removes the mapping for the specified key from this map if present.
	 * @param key key whose mapping is to be removed from the map
	 * @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 remove(Object key) {
		Entry<K, V> e = removeEntryForKey(key);
		return (e == null ? null : e.value);
	}

	/**
	 * Removes and returns the entry associated with the specified key in the
	 * HashMap. Returns null if the HashMap contains no mapping for this key.
	 * 移除并返回key对应的实体,如果找不到key返回null
	 */
	final Entry<K, V> removeEntryForKey(Object key) {
		if (size == 0) {
			return null;
		}
		int hash = (key == null) ? 0 : hash(key);
		int i = indexFor(hash, table.length);
		Entry<K, V> prev = table[i];
		Entry<K, V> e = prev;
		while (e != null) {
			Entry<K, V> next = e.next;
			Object k;
			if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
				//modCount++,每次数修改都会++,put,remove,如果迭代时发现modCount修改就会报快速迭代失败异常
				modCount++;
				size--;
				if (prev == e)
					table[i] = next;
				else
					prev.next = next;
				e.recordRemoval(this);
				return e;
			}
			prev = e;
			e = next;
		}
		return e;
	}

entrySet Iterator hasNext nextEntry

迭代是从下标0开始,下标为0的Entry迭代完,再迭代下标为1的,如果为1的Entry为空,跳过迭代为2的Entry
从代码中可以看出iterator.remove(); 迭代器的remove是会不导致快速迭代失败的,
private abstract class HashIterator<E> implements Iterator<E> {
        Entry<K,V> next;        // next entry to return
        int expectedModCount;   // For fast-fail
        int index;              // current slot
        Entry<K,V> current;     // current entry

        HashIterator() {
            expectedModCount = modCount;
            if (size > 0) { // advance to first entry
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
        }

        public final boolean hasNext() {
            return next != null;
        }

        final Entry<K,V> nextEntry() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();

            if ((next = e.next) == null) {
                Entry[] t = table;
                while (index < t.length && (next = t[index++]) == null)
                    ;
            }
            current = e;
            return e;
        }

        public void remove() {
            if (current == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            Object k = current.key;
            current = null;
            HashMap.this.removeEntryForKey(k);
            expectedModCount = modCount;
        }
    }

数据结构图:


迭代代码:

package com.util;

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

/**
 * @description
 * @date 2017/10/30
 * @see
 */
public class HashMapTest {

	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>(3);
		map.put("11", "11");
		map.put("12", "11");
		map.put("13", "11");
		map.put("14", "11");
		map.put("15", "11");
		map.put("19", "11");
		// 迭代是从下标0开始,下标为0的Entry迭代完,再迭代下标为1的,如果为1的Entry为空,跳过迭代为2的Entry
		for (Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator(); iterator.hasNext();) {
			Map.Entry<String, String> entry = iterator.next();
			System.out.print(entry.getKey() + "\t");
		}
	}
}

打印的结果15   13  14  19   11  12



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值