c.hashMap源码解析(1.7)

Hashmap的实现方法,俗称拉链法,其实是一种散列结构,其结构图(网络图片,这张图也挺好直接用了)如下

《c.hashMap源码解析(1.7)》

然后开始进入正题,解析hashmap源码的实现原理(由于1.8的hashmap与linkedHashmap做了比较大的改动,后面将重开一章解析1.8的这两种结构)

首先看他的类声明

public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable

中规中矩,实现了Cloneable与Serializable

属性

    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; //默认值16,通过移位操作

    
    static final int MAXIMUM_CAPACITY = 1 << 30;//规定最大容量,小于2的30次方

    static final float DEFAULT_LOAD_FACTOR = 0.75f;//很熟悉了,加载因子

    static final Entry<?,?>[] EMPTY_TABLE = {}; //空数组,一般用来作比较,或者作为初始值用

    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE; //table:正经用来存东西的,默认是空

    transient int size;//大小

    int threshold;//极限值,扩容时候作比较用

    final float loadFactor;//加载因子

    transient int modCount;//记录操作数,避免遍历或者多线程访问可能会出现的错误

    static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;//没看,先不看了
   transient int hashSeed = 0;//后面看到了再说

   //通过虚拟机配置来修改threshold值  
    private static class Holder {  
        static final int ALTERNATIVE_HASHING_THRESHOLD;  

        static {  
            String altThreshold = java.security.AccessController.doPrivileged(  
                new sun.security.action.GetPropertyAction(  
                    "jdk.map.althashing.threshold"));//读取配置值  

            int threshold;  
            try {  
                threshold = (null != altThreshold)//修改threshold值  
                        ? Integer.parseInt(altThreshold)  
                        : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;  


                if (threshold == -1) {  
                    threshold = Integer.MAX_VALUE;  
                }  

                if (threshold < 0) {  
                    throw new IllegalArgumentException("value must be positive integer.");  
                }  
            } catch(IllegalArgumentException failed) {  
                throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);  
            }  

            ALTERNATIVE_HASHING_THRESHOLD = threshold;  
        }  
    }  

构造方法

    //自定义初始容量与加载因子
    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();
    }


  <span style="white-space:pre">	</span>//使用默认加载因子0.75
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }


   //使用默认初始容量与默认加载因子
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }


   //根据size算好新map的初始容量,并且使用默认加载因子
    public HashMap(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        inflateTable(threshold);


        putAllForCreate(m);
    }
   //根据最小容量与容量*loadFactor算出比较小的一个作为极限值,创建一个新的Entry数组
<span style="white-space:pre">	</span>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);
    }

内部类

因为下面方法有所涉及,所有内部类先分析

Entry

 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;
        }
<span style="white-space:pre">	</span>//键跟值的hash异或
        public final int hashCode() {
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
        }
<span style="white-space:pre">	</span>
        public final String toString() {
            return getKey() + "=" + getValue();
        }

  
        void recordAccess(HashMap<K,V> m) {
        }


        void recordRemoval(HashMap<K,V> m) {
        }
    }

  

方法

<span style="font-family: Arial, Helvetica, sans-serif;"> </span><span style="font-family: Arial, Helvetica, sans-serif;">	</span><span style="font-family: Arial, Helvetica, sans-serif;">//添加entry,计算是否需要扩容,扩容之后根据hash与table.length计算桶的位置,然后加入进去</span>
    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);
        }

        createEntry(hash, key, value, bucketIndex);
    }

  <span style="white-space:pre">	</span>获取桶此位置上的entry,然后创建新的entry设置进去,这个设置新加入的元素将放在链表的头一个节点
    void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }

put

  //如果有key,修改值即可,如果没有调用addEntry,导致因加入的都在头结点上
    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);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

    //初始table
    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);
    }

    //也是遍历的方式找到key为null的,recordAccess这里是空,为linkedHashMap做了个铺垫
    private V putForNullKey(V value) {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0);
        return null;
    }

 按位与

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

resize

void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

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

transfer

//也是用两个循环,需要经过rehash,算出新的桶的位置,倒序
void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry<K,V> e : table) {
            while(null != e) {
                Entry<K,V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                int i = indexFor(e.hash, newCapacity);
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

putall

  
    public void putAll(Map<? extends K, ? extends V> m) {
        int numKeysToBeAdded = m.size();
        if (numKeysToBeAdded == 0)
            return;

        if (table == EMPTY_TABLE) {
            inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
        }

       //新加入的map size大于临界值的时候
        if (numKeysToBeAdded > threshold) {
            int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
            if (targetCapacity > MAXIMUM_CAPACITY)
                targetCapacity = MAXIMUM_CAPACITY;
            int newCapacity = table.length;
            while (newCapacity < targetCapacity)
                newCapacity <<= 1;
            if (newCapacity > table.length)
                resize(newCapacity);
        }
<span style="white-space:pre">	</span>还是一个个加入
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue());
    }

remove

 //删除元素,元素的键值为key  
    final Entry<K,V> removeEntryForKey(Object key) {  
        if (size == 0) {  
            return null;  
        }  
        int hash = (key == null) ? 0 : hash(key);//计算Hash值  
        int i = indexFor(hash, table.length);//定位Hash桶  
        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)))) {//在Hash桶中定位元素  
                modCount++;//更新修改次数  
                size--;//元素个数-1  
                if (prev == e)//是否是第一个元素  
                    table[i] = next;  
                else  
                    prev.next = next;//执行的是单链表的删除  
                e.recordRemoval(this);  
                return e;  
            }  
            prev = e;//单链表移动指针  
            e = next;  
        }  

        return e;  
    }  

    //删除一个Entry实体,这里通过o的key查找到元素,之后删除,和上面的实现类似  
    final Entry<K,V> removeMapping(Object o) {  
        if (size == 0 || !(o instanceof Map.Entry))//参数有效性验证  
            return null;  

        Map.Entry<K,V> entry = (Map.Entry<K,V>) o;  
        Object key = entry.getKey();  
        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;  
            if (e.hash == hash && e.equals(entry)) {  
                modCount++;  
                size--;  
                if (prev == e)  
                    table[i] = next;  
                else  
                    prev.next = next;  
                e.recordRemoval(this);  
                return e;  
            }  
            prev = e;  
            e = next;  
        }  

        return e;  
    }  

clear

 //清空Hash表  
    public void clear() {  
        modCount++;//更新修改次数  
        Arrays.fill(table, null);//底层数组置为null  
        size = 0;//元素个数为0  
    }  

浅复制

 //浅复制HashMap  ,只能获取引用值,获取不到值
    public Object clone() {  
        HashMap<K,V> result = null;  
        try {  
            result = (HashMap<K,V>)super.clone();  
        } catch (CloneNotSupportedException e) {  
            // assert false;  
        }  
        if (result.table != EMPTY_TABLE) {  
            result.inflateTable(Math.min(  
                (int) Math.min(  
                    size * Math.min(1 / loadFactor, 4.0f),  
                    // we have limits...  
                    HashMap.MAXIMUM_CAPACITY),  
               table.length));  
        }  
        result.entrySet = null;  
        result.modCount = 0;  
        result.size = 0;  
        result.init();  
        result.putAllForCreate(this);  

        return result;  
    }  

迭代器

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

    private final class ValueIterator extends HashIterator<V> {
        public V next() {
            return nextEntry().value;
        }
    }

    private final class KeyIterator extends HashIterator<K> {
        public K next() {
            return nextEntry().getKey();
        }
    }

keyset与value的迭代器都是用以上实现的。

隔了两个月,用伪代码重新看一遍逻辑,感觉理解的更加通顺一些

hashmap源码分析
*********************************************************
put
1.如果是空table,则根据默认容量初始化
2.如果是空key,调用putForNullKey
3.如果非空key,计算key的哈细值,然后根据table的length计算bucket的index
  遍历该bucket中的链表,如果有key,修改value,并且记录
4.modCount++
5.调用addEntry
*********************
addEntry
1.如果需要扩容,表长度乘以2,并且调用resize
2.计算hash值,当key==null,则hash为0
3.根据扩容后的length与key的哈细值,计算bucket的index
4.不管是否需要扩容,接下来执行创建createEntry
*******************
createEntry
1.Entry e=table[bucketindex];
2.e=table[bucketindex]=new Entry(hash,key,value,e);
3.size++;
********************
Entry 构造方法(每次插入的新元素都在链表头上)
  Entry(int h, K k, V v, Entry<K,V> n) {
  value = v;
  next = n;
   key = k;
   hash = h;

*****************************************************************

***************************
resize
拷贝一份table
有个关于最大容量的判断,不做关注
创建一个resize大小的空数组
调用transfer方法
table=newTable;
threshold=Math.min(newCapacity*loadFactor,Maximun_capacity+1);

transfer();
遍历数组
对于数组第一个元素,循环,重新定位槽,并且放在每个数组第一位
****************************

核心:HashIterator

用于EntrySet遍历

有个modcount,迭代器做操作会修改modcount,在迭代过程中不会报错

迭代过程就是找entry.next, 当next为null,找下一个槽,直到结束

Iterator i=map.entrySet().iterator();

while(i.hasNext()){

Entry e =(Entry) i.next();

e.getKey();

}

**************************

    原文作者:水银湖
    原文地址: https://blog.csdn.net/qq_25622107/article/details/52515350
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞