HashMap源码浅析jdk1.7

HashMap的成员变量和成员类

这里只拿出来主要的成员变量和内部类,具体的还请查看源码。

    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16   //默认容量
    static final int MAXIMUM_CAPACITY = 1 << 30; //最大容量
    static final float DEFAULT_LOAD_FACTOR = 0.75f;// 默认扩容因子
    static final Entry<?,?>[] EMPTY_TABLE = {};
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;// 维护的数组
    transient int size;// 当前的元素个数
    int threshold;//扩容的临界值,当内部元素个数超过这个值的时候,会进行扩容
    final float loadFactor;// 扩容因子
    transient int modCount;//记录修改的次数
static class Entry<K,V> implements Map.Entry<K,V> {
        final K key;
        V value;
        Entry<K,V> next;
        int hash;

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

        public final K getKey() {
            return key;
        }

        public final V getValue() {
            return value;
        }

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

        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }

        public final int hashCode() {
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
        }

        public final String toString() {
            return getKey() + "=" + getValue();
        }

        /**
         * This method is invoked whenever the value in an entry is
         * overwritten by an invocation of put(k,v) for a key k that's already
         * in the HashMap.
         */
        void recordAccess(HashMap<K,V> m) {
        }

        /**
         * This method is invoked whenever the entry is
         * removed from the table.
         */
        void recordRemoval(HashMap<K,V> m) {
        }
    }

hashMap的初始化

hashMap提供了三个构造方法,通过这三个方法来自定义初始化容量和扩容因子

无参构造:内部调用了两个参数的构造的方法,传递默认的容量16和扩容因子0.75,也就是说table数组的初始化大小是16,扩容的临界值是16*0.75=12,当存放的元素个数大于

12的时候就会扩容。(临界值=数组容量*扩容因子)

 public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);//调用两个参数的构造方法
    }

两个参数的构造方法:接收用户定义的容量和扩容因子,方法里面只不过是进行了数据验证并将临界值等于初始容量

 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;
        threshold = initialCapacity;// 这里临界值等于容量,在后面会进行改变
        init();
    }

一个参数的构造方法:内部调用了两个参数的构造的方法,传递用户设置的容量16和默认扩容因子

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

hashmap的初始化只不过进行了容量和扩容因子的设置,并没有将内部维护的数组长度设置成传递进来的容量,哪是什么时候设置的呢?带着疑问继续往下看

HashMap的put操作

hashmap进行put时首先会判断数组是不是那个空的数组,如果是空的数组调用inflateTable方法

 public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);//这里进行数组的初始化
        }
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);//计算key的hash码
        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))) {//如果key相同就更新值,且返回原来的值
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
//新添加的元素在链表中不存在,或者得到的索引位置没有元素,添加entry
        addEntry(hash, key, value, i);
        return null;
    }

下面来看看inflateTable方法做了什么

inflatTable方法接收设置的容量,然后调用roundUpToPowerOf2,roundUpToPowerOf2会将传递进来的数值A进行改变,返回的永远是一个2的n次幂的值B,A和B的关系是

A>=B=2^n 且A < 2^(n-1),也就是返回一个2的n次方的数,这个数大于A且最接近A,比如A=21    2^4=16<21< 2^5=32 那么返回的就是32 ,比如new HashMap(63);这里的capacity

就是64=2^6,可以打断点调试一下,之后改变临界值,实例化数组。

private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        int capacity = roundUpToPowerOf2(toSize);

        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        table = new Entry[capacity];
        initHashSeedAsNeeded(capacity);
    }

调试的结果如下:

内部的数组初始化化了之后再回到put方法

如果传递进来的key不为空,计算其哈希码并通过indexFor找到元素在数组中的索引,调用的方法是hash方法和indexFor方法,在计算在数组中的索引的时候,将键hash码与

数组的最大索引(数组长度减1)按位与,来确保不会越界,比如一个元素的hash码是‭2125768333‬转换成二进制是1111110101101001010011010001101,数组的容量是64,那最大索引就是63,二进制为‭111111‬ ,按位与后有效位为最大索引的二进制中1的位数,从而确保不会越界

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

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

然后判断数组该索引处是否有元素存在,如果有元素存在就遍历该元素的链表,看新添加的元素是否存在链表中,如果存在链表中就更新值,并返回原来的值,新添加的元素在链表中不存在,或者得到的索引位置没有元素,添加entry调用addEntry方法

 void addEntry(int hash, K key, V value, int bucketIndex) {
       // 如果元素个数大于等于临界值进行扩容
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }
        //创建entry
        createEntry(hash, key, value, bucketIndex);
    }
 void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];//获取原来该索引的entry
        table[bucketIndex] = new Entry<>(hash, key, value, e);//如果原来该索引处有元素,替换为新的,数组中存储的是最后插入的,原来的entry链到新entry的后面
        size++;
    }

打个比方, 第一个键值对A进来,通过计算其key的hash得到的index=0,记做:Entry[0] = A。一会后又进来一个键值对B,通过计算其index也等于0,现在怎么办?HashMap会这样做:B.next = A,Entry[0] = B,如果又进来C,index也等于0,那么C.next = B,Entry[0] = C;这样我们发现index=0的地方其实存取了A,B,C三个键值对,他们通过next这个属性链接在一起。所以疑问不用担心。也就是说数组中存储的是最后插入的元素。到这里为止,HashMap的put就完成了。

HahsMap的get操作

public V get(Object key) {
        if (key == null)
            return getForNullKey();
        Entry<K,V> entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }
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;
    }

和元素添加到数组的时候一样,通过计算key的hash码,再找到元素在数组中的索引然后遍历链表,进行比较最后返回entry,再getValue获取值

原文地址:https://www.cnblogs.com/kin1492/p/9354698.html