HashMap-jdk1.7

    @Test
    public void asda() {
        Map map = new HashMap<>();
        map.put("1", "2");
    }

首先从最常用的构造方法开始

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

loadFactor为负载因子,默认值0.75.

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    /**
     * The load factor used when none specified in constructor.
     */
    static final float DEFAULT_LOAD_FACTOR = 0.75f;

接下来以put方法作为切入点来进行源码分析。

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

1.hashmap存储元素的本质是一个数组。inflateTable可以看到数组的初始化是在第一次put的时候进行的

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

关于数组大小,为2的幂次方,如果初始化的时候不是2的幂次方,会向上取2的幂次方.比如说初始指定大小10,roundUpToPowerOf2函数运算会返回2^4=16。

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

threshold为负载容量,当对象个数超过这个值并满足 一定条件的时候就会进行resize操作。
initHashSeedAsNeeded主要用于hashseed的计算,和key的hash值计算有关。
2.先不管key为null的情况,先看hash,indexFor,即hashmap的key的hash散列过程。

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

可以看到非string的key的hash都是一系列的位运算,主要和之前说过的hashseed有关。

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

散列过程采用的是与运算,这样散列出来的值范围为[0,length)。
3.经过上面的过程,得出i就是元素在数组中的位置下标。如果两个不一样的key的散列值一样,就会在同一个数组位置上采用链表结构。数组元素的结构如下。

 Entry(int h, K k, V v, Entry n) {
            value = v;
            next = n;
            key = k;
            hash = h;
  }

由此不难理解下面这段代码的作用是为了覆盖同一个key的元素。

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

if (e.hash == hash && ((k = e.key) == key || key.equals(k)))从这段代码可以看出hashmap对于key重复的判定是hash值相等并且key相等(==用于基本类型的比较;比的是对象的内存地址,非基本类型调用equals方法)
4.如果key没有重复,那就要进行新插入操作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);
        }

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

当对象数量>=负载容量threshold并且当前元素的下表对应的数组位置不为空的时候就会进行扩容操作,扩容的规则为*2。扩容的过程中又会重新计算下hashseed。

  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就是个将数据从旧数组搬到新数组的过程。

 void transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
        for (Entry e : table) {
            while(null != e) {
                Entry 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;
            }
        }
    }

这里指的注意的是最好三行代码,这个顺序可以看出:在key的hash散列值一样的时候,新插入元素会在表头,即数组元素的位置上。比如说table[3]=a,a.next=b.这时候来了个c,key的hash散列值和a一样,就会变成table[3]=c,c.next=a,a.next=b。这一点从后面的插入操作createEntry也可以看出来。

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

5.这时候再来看key为null的操作就非常简单了。

 private V putForNullKey(V 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;
    }

你可能感兴趣的:(HashMap-jdk1.7)