jdk1.7源码解读

1.HashMap数据结构

HashMap的数据结构是数组+链表的形式(Entry[]),示意图如下:


image.png

2.HashMap成员变量

    /**hashMap默认容量,1<<4=16**/
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

    /**hashMap最大容量**/
    static final int MAXIMUM_CAPACITY = 1 << 30;

    /**
     * The load factor used when none specified in constructor.
     * 默认加载因子0.75
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * An empty table instance to share when the table is not inflated.
     */
    static final Entry[] EMPTY_TABLE = {};

    /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */
    /**存数据的地方----> table的长度会自动扩容成2的次方**/
    transient Entry[] table = (Entry[]) EMPTY_TABLE;

    /**
     * The number of key-value mappings contained in this map.
     */
    /**存在该map中键值对的数量**/
    transient int size;

    /**
     * The next size value at which to resize (capacity * load factor).
     * @serial
     */
    // If table == EMPTY_TABLE then this is the initial capacity at which the
    // table will be created when inflated.
    /** 临界值(HashMap 实际能存储的大小),公式为(threshold = capacity * loadFactor) */
    int threshold;

    /**加载因子**/
    final float loadFactor;

    /** HashMap的结构被修改的次数,用于迭代器 */
    transient int modCount;

    /**
     * The default threshold of map capacity above which alternative hashing is
     * used for String keys. Alternative hashing reduces the incidence of
     * collisions due to weak hash code calculation for String keys.
     * 

* This value may be overridden by defining the system property * {@code jdk.map.althashing.threshold}. A property value of {@code 1} * forces alternative hashing to be used at all times whereas * {@code -1} value ensures that alternative hashing is never used. */ static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;

3.HashMap构造方法

  • 1.7版本HashMap的构造方法有四个,分别是:
    public HashMap();
    public HashMap(int initialCapacity);
    public HashMap(int initialCapacity, float loadFactor);
    public HashMap(Map m);// 只有该构造方法会初始化table,另外三个构造方法不会

其中HashMap()、HashMap(int initialCapacity)都是调用构造方法HashMap(int initialCapacity, float loadFactor),下面将介绍HashMap(int initialCapacity, float loadFactor)的源码:

/**
     * Constructs an empty HashMap 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);

        /** 注意:在此处并没有直接初始化table,在其第一次put时才会去初始化**/

        this.loadFactor = loadFactor;
        //此处threshold 指定为initialCapacity,在后续inflateTable会替换成Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1)
        threshold = initialCapacity;
        init(); //该类中没有实现,在其子类LinkedHashMap中有实现
    }

下面将会介绍HashMap(Map m)的源码:

/**
     * Constructs a new HashMap with the same mappings as the
     * specified Map.  The HashMap is created with
     * default load factor (0.75) and an initial capacity sufficient to
     * hold the mappings in the specified Map.
     *
     * @param   m the map whose mappings are to be placed in this map
     * @throws  NullPointerException if the specified map is null
     */
    public HashMap(Map m) {
        // 调用构造方法初始化
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        // table初始化
        inflateTable(threshold);

        putAllForCreate(m);
    }

    private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        // capacity为大于等于指定容量的最小2的次方
        // 比如initialCapacity=3,capacity=4
        int capacity = roundUpToPowerOf2(toSize);

        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        table = new Entry[capacity];
        initHashSeedAsNeeded(capacity); // 选择合适的Hash因子
    }

    private void putAllForCreate(Map m) {
        // 遍历传入的map进行逐个添加
        for (Map.Entry e : m.entrySet())
            putForCreate(e.getKey(), e.getValue());
    }

/**
     * This method is used instead of put by constructors and
     * pseudoconstructors (clone, readObject).  It does not resize the table,
     * check for comodification, etc.  It calls createEntry rather than
     * addEntry.
     */
    private void putForCreate(K key, V value) {
        int hash = null == key ? 0 : hash(key);
        int i = indexFor(hash, table.length);

        /**
         * Look for preexisting entry for key.  This will never happen for
         * clone or deserialize.  It will only happen for construction if the
         * input Map is a sorted map whose ordering is inconsistent w/ equals.
         */
        for (Entry e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                e.value = value;
                return;
            }
        }

        // 初始化时不会将modCount++,因为初始化不能理解为对map的修改

        // 创建一个entry,后续对该方法进行详细介绍
        createEntry(hash, key, value, i);
    }

4.HashMap.put(K key, V value)方法详解

首先通过一个流程图了解其过程:


image.png

接下来对源码进行介绍:

    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            // 初始化table
            inflateTable(threshold);
        }
        // 添加key=null的节点
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key);
        int i = indexFor(hash, table.length);

        // 查找之前这个key是否存在,存在直接替换value并返回之前的value,否则添加节点
        // 需要遍历
        for (Entry 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;
    }

    

step1: 判断table是否被初始化,未初始化则调用inflateTable(threshold);进行初始化
step2: 判断key==null?若是,则调用putForNullKey(value)并返回,putForNullKey(value)源码如下:

private V putForNullKey(V value) {
        // 从table[0]的节点进行遍历得到key=null的直接,并返回对应的value
        for (Entry 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;
    }

step3: 遍历链表看是否存在该key,若存在则替换value并返回,否则调用addEntry方法,如下:

void addEntry(int hash, K key, V value, int bucketIndex) {
        // 如果当前size已经大于等于临界值(threshold),并且需要插入的value所对应的下标在数组中已经存在链表,需要进行扩容(resize)
        // 扩容默认*2
        if ((size >= threshold) && (null != table[bucketIndex])) {
            resize(2 * table.length);
            // 重新计算key的hash和下标
            hash = (null != key) ? hash(key) : 0;
            bucketIndex = indexFor(hash, table.length);
        }

        // 在头部添加节点
        createEntry(hash, key, value, bucketIndex);
    }

step4: 判断是否需要扩容,若需要则调用resize方法

 void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        // 如果之前的容量已经是最大值了,那么这边把临界值调整为最大的Int值并返回-->2^32-1
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

        Entry[] newTable = new Entry[newCapacity];
        // 将数据迁移到新的table中
        transfer(newTable, initHashSeedAsNeeded(newCapacity));
        table = newTable;
        // 重新计算临界值threshold
        threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }

    void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry e : table) {
            while(null != e) {
                Entry next = e.next;
                // 判断是否需要重新计算hash值
                if (rehash) {
                    e.hash = null == e.key ? 0 : hash(e.key);
                }
                // 重新计算下标
                int i = indexFor(e.hash, newCapacity);
                // 将当前的e放在 其下标在新table中对应的链表(newTable[i]) 之前
                e.next = newTable[i];
                newTable[i] = e;
                e = next;
            }
        }
    }

step5: 调用createEntry在链表头部添加该元素:

     void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }


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

5.HashMap.get(Object key)方法详解

HashMap的get方法相对应put来说就非常的简单了,就是遍历对应的链表进行数据返回,源码如下:

    public V get(Object key) {
        // 获取key=null的值
        if (key == null)
            return getForNullKey();
        Entry entry = getEntry(key);

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

    /**key==null的处理方式**/
    private V getForNullKey() {
        if (size == 0) {
            return null;
        }
        for (Entry e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }


    final Entry getEntry(Object key) {
        if (size == 0) {
            return null;
        }

        int hash = (key == null) ? 0 : hash(key);
        // 遍历查找key值
        for (Entry 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;
    }

6.HashMap.remove(Object key)方法详解

image.png
    public V remove(Object key) {
        Entry e = removeEntryForKey(key);
        return (e == null ? null : e.value);
    }

    final Entry removeEntryForKey(Object key) {
        if (size == 0) {
            return null;
        }
        int hash = (key == null) ? 0 : hash(key);
        int i = indexFor(hash, table.length);
        Entry prev = table[i];
        Entry e = prev;

        while (e != null) {
            Entry next = e.next;
            Object k;
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k)))) {
                modCount++;
                size--;
                // 如果移除的刚好是第一个节点,那么直接把e.next赋给table[i]
                if (prev == e)
                    table[i] = next;
                else
                    // 如果非第一个节点,e.prev.next = e.next
                    prev.next = next;
                e.recordRemoval(this);
                return e;
            }
            prev = e;
            e = next;
        }

        return e;
    }

未完待续。。。

你可能感兴趣的:(jdk1.7源码解读)