分析 HashMap 新增元素:(JDK1.7 )

    1. public v put(K key , V value) {
    2. int hash = hash(key) ;
    3. int i= indexFor(hash , table.length);
    4. //该循环通过hashCode返回值找到对应的数组下标位置
    5. //如果equals 结果为true, 则覆盖原值,如果都为 false ,则添加元素
    6. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
    7. Object k;
    8. //如果Keyhash是相同的.那么再进行如下判断
    9. // key是同一个对象或者equals返回为true,则覆盖原来的value值
    10. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
    11. V oldValue = e.value;
    12. e.value = value;
    13. e.recordAccess(this);
    14. return oldValue;
    15. }
    16. }
    17. //
    18. modCount++;
    19. // 添加元素
    20. addEntry(hash, key, value, i);
    21. return null;
    22. }
    1. void addEntry(int hash, K key, V value, int bucketIndex) {
    2. if ((size >= threshold) && (null != table[bucketIndex])) {
    3. resize(2 * table.length);
    4. hash = (null != key) ? hash(key) : 0;
    5. bucketIndex = indexFor(hash, table.length);
    6. }
    7. createEntry(hash, key, value, bucketIndex);
    8. }
    1. //1.7中插入元素时,插入在头部,而不是尾部
    2. void createEntry(int hash, K key, V value, int bucketIndex) {
    3. Entry<K,V> e = table[bucketIndex];
    4. //如果已经形成链表,就将链表挂在新插入的节点
    5. table[bucketIndex] = new Entry<>(hash, key, value, e);
    6. size++;
    7. }