1. HashMap添加元素

HashMap添加元素的步骤

  1. 获取Key的hash值 -- hashCode()
  2. 利用hash值计算在数组中的下标
  3. 判断下标上是否有元素

3.1 没有元素 -- 直接添加

3.2 有元素 -- 判断元素之间是否相同((hash)&&(==||equals))

3.2.1 不相同,添加(JDK1.7头插法,1.8尾插法)

3.2.2 相同,替换原来的Value(达到去重的效果)

2023年6月23日,HashMap添加元素_尾插法

1.8尾插法package com.wz.HashMap_class;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class test01 {
    public static void main(String[] args) {
        HashMap<Student, String> map = new HashMap<>();
        map.put(new Student("张三",18,'男',"2023001","001"),"唱歌");
        map.put(new Student("李四",19,'女',"2023001","002"),"跳舞");
        map.put(new Student("王五",20,'男',"2023002","003"),"RAP");
        map.put(new Student("赵六",21,'女',"2023002","003"),"打篮球");
        map.put(null,"踢足球");
        map.put(null,"打篮球");

        Set<Map.Entry<Student, String>> entries = map.entrySet();
        for (Map.Entry<Student,String> entry:entries
             ) {
            Student key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key+"------"+value);
        }
    }
}
//JDK1.8尾插法

2023年6月23日,HashMap添加元素_HashMap_02

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>{
    //默认初始化容量(必须是2的幂)
    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 = {};
    //hash数组/hash表
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;//new Entry[16];
    //元素个数
    transient int size;//0
    //阈值/扩容界限(数组长度*负载因子)
    int threshold;//12
    //负载因子
    final float loadFactor;//0.75
    //外部操作数
    transient int modCount;//0
    //hash种子数
    transient int hashSeed = 0;
    
}