Map in Java (detailed explanation of three types of double-column collections)

Click to view the detailed explanation of the single-column set Set 10,000 words: It also includes hash interpretation and underlying analysis.


Preface

双列集合的特点:
①双列集合一次需要存一对数据,分别为键和值
②键不能重复,值可以重复
③键和值是一一对应的,每一个键只能找到自己对应的值
④键+值这个整体我们称之为“键值对”或者“键值对对象”,在Java中叫做“Entry对象”

1. Map

In the collection in Map, elements exist in pairs (understood as couples). Each element consists of two parts: key and value. The corresponding value can be found through the key.
Create objects of Map collection: Because Map is an interface and objects cannot be created directly, we use polymorphism to create them. Here we can create objects that implement class HashMap.

1. Commonly used APIs for Map collections

method name illustrate
V put(Object key, V value) Add element
V remove(Object key) Delete key-value pair elements based on key
void clear() Clear all elements in the Map
boolean containsKey(Object key) Determine whether the collection contains the specified key
boolean containsValue(Object value) Determine whether the set contains the specified value
boolean isEmpty() Determine whether the collection is empty
int size() Get the length of the collection, that is, the number of keys in the collection
V get(Object key) Get value based on key
Set KeySet() Get the set of all keys
Collection values() Get the set of all values
Set<Map.Entry<K,V>> entrySet() Get a collection of all key-value objects
V getOrDefault(Object key, V defaultValue) When there is this key in the Map collection, the value corresponding to this key is used. If not, the default value defaultValue is used.
default void forEach(BiConsumer<? super K, ? super V> action)) Combining Lambda to traverse Map collection## Title

Code demo:

1.Basic functions of Map collection

package com.zzu.map;

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

public class Demo1 {
    
    
    public static void main(String[] args) {
    
    
        //1.创建Map集合的对象
        Map<String,String> m =new HashMap<>();//创建HashMap对象

        //2.添加元素
        //put方法的细节:
        //添加/覆盖
        //在添加数据的时候,如果键不存在,那么直接把键值对对象添加到map集合当中,方法返回null
        //在添加数据的时候,如果键是存在的,那么会把原有的键值对对象覆盖,会把被覆盖的值进行返回。
        m.put("yj", "jh");//key value
        m.put("天才","笨蛋");
        m.put("余卷卷","鱼卷卷");

        System.out.println(m.remove("yj"));//jh
        System.out.println(m);

        //3.判断是否包含
        //containsKey(键)
        //containsValue(值)
        System.out.println(m.containsKey("天才"));//true
        System.out.println(m.containsValue("jh"));//false jh已经被remove
        
        //4.判断是否为空
        System.out.println(m.isEmpty());//false
        System.out.println(m.size());//2
        
        //5.清空操作
        m.clear();//清空
        System.out.println(m.isEmpty());//true
        System.out.println(m.size());//0

    }
}


Output result:

jh
{
    
    余卷卷=鱼卷卷, 天才=笨蛋}
true
false
false
2
true
0

2.Map collection acquisition function

package com.zzu.map;

import java.util.*;

public class Demo2 {
    
    
    public static void main(String[] args) {
    
    
        Map<String,String> m =new HashMap<>();
        m.put("yj", "jh");//key value
        m.put("天才","笨蛋");
        m.put("余卷卷","鱼卷卷");

        System.out.println(m.get("yj"));//获取jh
        System.out.println("----------");

        System.out.println(m.keySet());//获取键集合
        Set<String> ketSet=m.keySet();
        for(String s:ketSet){
    
    
            System.out.println(s);
        }
        System.out.println("----------");

        System.out.println(m.values());//获取值集合
        Collection<String> collection=m.values();
        for(String s:collection){
    
    
            System.out.println(s);
        }
        System.out.println("----------");

        System.out.println(m.entrySet());//获取所有键值对象集合
        Set<Map.Entry<String,String>> setMapEntry = m.entrySet();
        System.out.println(setMapEntry);
    }
}

Output result:

jh
----------
[yj, 余卷卷, 天才]
yj
余卷卷
天才
----------
[jh, 鱼卷卷, 笨蛋]
jh
鱼卷卷
笨蛋
----------
[yj=jh, 余卷卷=鱼卷卷, 天才=笨蛋]
[yj=jh, 余卷卷=鱼卷卷, 天才=笨蛋]

3.Map’s getOrDefault() method

package com.zzu.map;

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

public class Demo3 {
    
    
    public static void main(String[] args) {
    
    
        Map<String,String> m =new HashMap<>();
        m.put("yj", "jh");//key value
        m.put("天才","笨蛋");
        m.put("余卷卷","鱼卷卷");

        //键中存在yj,所以会使用value
        //键中不存在天才皓,所以会使用默认值
        System.out.println(m.getOrDefault("yj", "111"));//jh
        System.out.println(m.getOrDefault("天才皓", "666"));//666
    }
}

2.Three traversals of Map collections

1. Key to find value, value to find key

package com.zzu.map;

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

public class Demo4 {
    
    
    public static void main(String[] args) {
    
    
        //Map集合的第一种遍历方式

        //1.创建Map集合对象
        Map<String,String> m =new HashMap<>();

        //2.添加元素
        m.put("yj", "jh");
        m.put("天才","笨蛋");
        m.put("余卷卷","鱼卷卷");

        //3.通过键找值
        //3.1 获取所有键,把这些键放入单列集合中
        Set<String> ketSet=m.keySet();
        //3.2遍历单列集合,得到每一个键
        for(String s:ketSet){
    
    
            //System.out.println(s);
            //3.3 利用map集合中的键获取对应的值  get
            String value = m.get(s);
            System.out.println(s + " = " + value);
        }

        //4.通过键找值
        //4.1 获取所有值,把这些值放入集合中
        Collection<String> collection=m.values();
        //4.2遍历集合,得到每一个值
        for(String s:collection){
    
    
            System.out.println(s);
        }
    }

}


yj = jh
余卷卷 = 鱼卷卷
天才 = 笨蛋
jh
鱼卷卷
笨蛋

2. Key-value pairs

package com.zzu.map;

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

public class Demo5 {
    
    
    public static void main(String[] args) {
    
    
        //Map集合的第二种遍历方式

        //1.创建Map集合对象
        Map<String,String> m =new HashMap<>();

        //2.添加元素
        m.put("yj", "jh");
        m.put("天才","笨蛋");
        m.put("余卷卷","鱼卷卷");

        //3.通过键值对遍历
        //3.1 通过一个方法获取所有的键值对对象,返回一个Set集合
        Set<Map.Entry<String,String>> setMapEntry = m.entrySet();
        //3.2 遍历entries这个集合,去得到里面的每一个键值对对象
        for(Map.Entry<String,String> entry:setMapEntry){
    
    
            //3.3 利用entry调用get方法获取键和值
            System.out.println(entry.getKey()+"="+entry.getValue());
        }

    }
}

yj=jh
余卷卷=鱼卷卷
天才=笨蛋

3.Lambda expression

package com.zzu.map;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

public class Demo6 {
    
    
    public static void main(String[] args) {
    
    
        //Map集合的第三种遍历方式

        //1.创建Map集合对象
        Map<String,String> m =new HashMap<>();

        //2.添加元素
        m.put("yj", "jh");
        m.put("天才","笨蛋");
        m.put("余卷卷","鱼卷卷");

        //3.利用lambda表达式进行遍历
        //底层:
        //forEach其实就是利用第二种方式进行遍历,依次得到每一个键和值
        //再调用accept方法
        m.forEach(new BiConsumer<String, String>() {
    
    
            @Override
            public void accept(String key, String value) {
    
    
                System.out.println(key + "=" + value);
            }
        });

        System.out.println("-----------------------------------");

        //简化!
        m.forEach((String key, String value)->{
    
    
                    System.out.println(key + "=" + value); 
                }
        );

        System.out.println("-----------------------------------");

        //再简化!!
        m.forEach((key, value)-> System.out.println(key + "=" + value));

    }
}

yj=jh
余卷卷=鱼卷卷
天才=笨蛋
-----------------------------------
yj=jh
余卷卷=鱼卷卷
天才=笨蛋
-----------------------------------
yj=jh
余卷卷=鱼卷卷
天才=笨蛋

2. HashMap

Features of HashMap:
①HashMap is an implementation class in Map
②There are no additional special methods that need to be learned, just use the methods in Map directly That’s it
③The characteristics are all determined by keys: disordered, non-repetitive, and no index
④The underlying principles of HashMap and HashSet are exactly the same, both are haha Hash table structure

Insert image description here
Summary:
.1. The bottom layer of HashMap is a hash table structure
2. Rely on the hashCode method and the equal method to ensure the uniqueness of the key a>
3. If the key stores a custom object, you need to rewrite the hashCode and equals methods
If the value stores a custom object, you do not need to rewrite the hashCode and equals methods

1.HashMap stores custom objects to achieve unique key values

   /*
    需求:创建一个HashMap集合,键是学生对象(Student),值是籍贯(String)。
    存储几个键值对元素,并遍历
    要求:同姓名,同年龄认为是同一个学生

    核心点:
        HashMap的键位置如果存储的是自定义对象,需要重写hashCode和equals方法。(实现去重)
   */

code show as below:

package com.zzu.HashMap;

import java.util.Objects;

public class Student {
    
    
    private String name;
    private int age;

    public Student() {
    
    
    }

    public Student(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
    
    
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
    
    
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
    
    
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
    
    
        this.age = age;
    }

    //重写HashCode和equals方法
    @Override
    public boolean equals(Object o) {
    
    
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
    
    
        //return Objects.hash(name, age);
        return name.hashCode();
    }
    
    //重写toString()方法,目的性打印
    public String toString() {
    
    
        return "Student{name = " + name + ", age = " + age + "}";
    }
}

package com.zzu.HashMap;


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

public class Demo1 {
    
    
    public static void main(String[] args) {
    
    
       /*
        需求:创建一个HashMap集合,键是学生对象(Student),值是籍贯(String)。
        存储几个键值对元素,并遍历
        要求:同姓名,同年龄认为是同一个学生

        核心点:
            HashMap的键位置如果存储的是自定义对象,需要重写hashCode和equals方法。(实现去重)
       */


        //1.创建HashMap的对象
        HashMap<Student,String> m = new HashMap<>();

        //2.创建五个学生对象
        Student s1 = new Student("zzu_yj",20);
        Student s2 = new Student("zzu_jh",19);
        Student s3 = new Student("yj",20);
        Student s4 = new Student("jh",19);
        Student s5 = new Student("jh",19);

        //3.添加元素
        m.put(s1,"郑州");
        m.put(s2,"郑州");
        m.put(s3,"驻马店");
        m.put(s4,"鹤壁");
        m.put(s5,"鹤壁");//去重

        //4.遍历集合(已去重)
        //获取键值遍历
        Set<Student> keys = m.keySet();
        for (Student key : keys) {
    
    
            String value = m.get(key);
            System.out.println(key + "=" + value);
        }

        System.out.println("--------------------------");

        //键值对遍历
        Set<Map.Entry<Student, String>> entries = m.entrySet();
        for (Map.Entry<Student, String> entry : entries) {
    
    
            Student key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + "=" + value);
        }

        System.out.println("--------------------------");

        //Lambda表达式遍历
        m.forEach((student, s)-> System.out.println(student + "=" +  s));

    }
}
Student{
    
    name = yj, age = 20}=驻马店
Student{
    
    name = zzu_jh, age = 19}=郑州
Student{
    
    name = zzu_yj, age = 20}=郑州
Student{
    
    name = jh, age = 19}=鹤壁
--------------------------
Student{
    
    name = yj, age = 20}=驻马店
Student{
    
    name = zzu_jh, age = 19}=郑州
Student{
    
    name = zzu_yj, age = 20}=郑州
Student{
    
    name = jh, age = 19}=鹤壁
--------------------------
Student{
    
    name = yj, age = 20}=驻马店
Student{
    
    name = zzu_jh, age = 19}=郑州
Student{
    
    name = zzu_yj, age = 20}=郑州
Student{
    
    name = jh, age = 19}=鹤壁

2. Use Map collection for statistics

     /*
     需求:
        某个班级80名学生,现在需要组成秋游活动,
        班长提供了四个景点依次是(A、B、C、D),
        每个学生只能选择一个景点,请统计出最终哪个景点想去的人数最多。
    */
package com.zzu.HashMap;

import java.util.*;

public class Demo2 {
    
    
    public static void main(String[] args) {
    
    
         /*
            某个班级80名学生,现在需要组成秋游活动,
            班长提供了四个景点依次是(A、B、C、D),
            每个学生只能选择一个景点,请统计出最终哪个景点想去的人数最多。
        */
        //1.需要先让同学们投票
        //定义一个数组,存储4个景点
        String[] arr = {
    
    "A","B","C","D"};
        //利用随机数模拟80个同学的投票,并把投票的结果存储起来
        ArrayList<String> list = new ArrayList<>();
        Random r = new Random();
        for (int i = 0; i < 80; i++) {
    
    
            int index = r.nextInt(arr.length);
            list.add(arr[index]);
        }

        //2.如果要统计的东西比较多,不方便使用计数器思想
        //我们可以定义map集合,利用集合进行统计。
        /**
         * 当然对于第一步和第二步
         * 我们可以直接创建HashMap对象,使用getOrDefault()方法统计
         */
        HashMap<String,Integer> m = new HashMap<>();
        for (String name : list) {
    
    
            //判断当前的景点在map集合当中是否存在
            if(m.containsKey(name)){
    
    
                //存在
                //先获取当前景点已经被投票的次数
                int count = m.get(name);
                //表示当前景点又被投了一次
                count++;
                //把新的次数再次添加到集合当中
                m.put(name,count);
            }else{
    
    
                //不存在
                m.put(name,1);
            }
        }

        System.out.println(m);

        //3.求最大值
        int max = 0;
        Set<Map.Entry<String, Integer>> entries = m.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
    
    
            int count = entry.getValue();
            if(count > max){
    
    
                max = count;
            }
        }
        System.out.println(max);

        //4.判断哪个景点的次数跟最大值一样,如果一样,打印出来
        for (Map.Entry<String, Integer> entry : entries) {
    
    
            int count = entry.getValue();
            if(count == max){
    
    
                System.out.println(entry.getKey());
            }
        }

    }
}

{
    
    A=25, B=17, C=20, D=18}
25
A

3. LinkedHashMap

           由键决定:
               有序、不重复、无索引。
           有序:
               保证存储和取出的顺序一致
           原理:
               底层数据结构是依然哈希表,只是每个键值对元素又额外的多了一个双链表的机制记录存储的顺序。

Code demo:

package com.zzu.LinkedHashMap;

import java.util.LinkedHashMap;

public class Demo1 {
    
    
    public static void main(String[] args) {
    
    
  /*
           LinkedHashMap:
               由键决定:
                   有序、不重复、无索引。
               有序:
                   保证存储和取出的顺序一致
               原理:
                   底层数据结构是依然哈希表,只是每个键值对元素又额外的多了一个双链表的机制记录存储的顺序。
         */



        //1.创建集合
        LinkedHashMap<String,Integer> lhm = new LinkedHashMap<>();

        //2.添加元素
        lhm.put("yj", 20);
        lhm.put("天才皓",19);
        lhm.put("天才皓",19);
        lhm.put("余卷卷",20);
        lhm.put("鱼卷卷",20);

        //3.打印集合
        System.out.println(lhm)
    }
}

{
    
    yj=20, 天才皓=19, 余卷卷=20, 鱼卷卷=20}

4. TreeMap

TreeMap跟TreeSet底层原理一样,都是红黑树结构的。

底层基于红黑树实现排序,增删查改性能较好

由键决定特性:不重复、无索引、可排序

可排序:对键进行排序。
注意:默认按照键的从小到大进行排序,也可以自己规定键的排序规则

There are two sorting rules for code writing:

实现Comparable接,指定比较规则。
创建集合时传递Comparator比较器对象,指定比较规则。

1. Pass the Comparator comparator

        需求1:
            键:整数表示id
            值:字符串表示商品名称
            要求1:按照id的升序排列

            要求2:按照id的降序排列
package com.zzu.TreeMap;

import java.util.Comparator;
import java.util.TreeMap;

public class Demo1 {
    
    
    public static void main(String[] args) {
    
    
        /*
           TreeMap集合:基本应用
            需求1:
                键:整数表示id
	            值:字符串表示商品名称
	            要求1:按照id的升序排列

	            要求2:按照id的降序排列
         */

        //1.创建集合对象
        //Integer Double 默认情况下都是按照升序排列的
        //String 按照字母再ASCII码表中对应的数字升序进行排列
        //abcdefg ...
        TreeMap<Integer,String> tm = new TreeMap<>(new Comparator<Integer>() {
    
    
            @Override
            public int compare(Integer o1, Integer o2) {
    
    
                //o1:当前要添加的元素
                //o2:表示已经在红黑树中存在的元素
                return o2 - o1;
            }
        });

        //2.添加元素
        tm.put(4,"雷碧");
        tm.put(3,"九个核桃");
        tm.put(5,"可恰可乐");
        tm.put(2,"康帅傅");
        tm.put(1,"粤利粤");

        //3.打印集合
        System.out.println(tm);
    }
}

{
    
    5=可恰可乐, 4=雷碧, 3=九个核桃, 2=康帅傅, 1=粤利粤}

2. Key customization object

        需求2:
            键:学生对象
            值:籍贯
            要求:按照学生年龄的升序排列,年龄一样按照姓名的字母排列,同姓名年龄视为同一个人。
package com.zzu.TreeMap;

public class Student implements Comparable<Student>{
    
    
    private String name;
    private int age;


    public Student() {
    
    
    }

    public Student(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
    
    
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
    
    
        this.name = name;
    }

    /**
     * 获取
     * @return age
     */
    public int getAge() {
    
    
        return age;
    }

    /**
     * 设置
     * @param age
     */
    public void setAge(int age) {
    
    
        this.age = age;
    }

    public String toString() {
    
    
        return "Student{name = " + name + ", age = " + age + "}";
    }

    @Override
    public int compareTo(Student o) {
    
    
        //按照学生年龄的升序排列,年龄一样按照姓名的字母排列,同姓名年龄视为同一个人。

        //this:表示当前要添加的元素
        //o:表示已经在红黑树中存在的元素

        //返回值:
        //负数:表示当前要添加的元素是小的,存左边
        //正数:表示当前要添加的元素是大的,存右边
        //0:表示当前要添加的元素已经存在,舍弃

        int i = this.getAge() - o.getAge();
        i = i == 0 ? this.getName().compareTo(o.getName()) : i;
        return i;
    }
}

package com.zzu.TreeMap;

import com.zzu.a04mytreemap.Student;

import java.util.TreeMap;

public class Demo2 {
    
    
    public static void main(String[] args) {
    
    
        /*
           TreeMap集合:基本应用
            需求2:
                键:学生对象
	            值:籍贯
	            要求:按照学生年龄的升序排列,年龄一样按照姓名的字母排列,同姓名年龄视为同一个人。
         */


        //1.创建集合
        TreeMap<Student,String> tm = new TreeMap<>();

        //2.创建三个学生对象
        Student s1 = new Student("jianghao",19);
        Student s2 = new Student("yujun",20);
        Student s3 = new Student("yjj",20);

        //3.添加元素
        tm.put(s1,"鹤壁");
        tm.put(s2,"驻马店");
        tm.put(s3,"郑州");

        //4.打印集合
        System.out.println(tm);
    }
}

{
    
    Student{
    
    name = jianghao, age = 19}=鹤壁, Student{
    
    name = yjj, age = 20}=郑州, Student{
    
    name = yujun, age = 20}=驻马店}

3.TreeMap counts the number of characters

需求:
    字符串“aababcabcdabcde”
    请统计字符串中每一个字符出现的次数,并按照以下格式输出
    输出结果:
    a(5)b(4)c(3)d(2)e(1)

New statistical ideas: using map collections for statistics

      如果题目中没有要求对结果进行排序,默认使用HashMap
      如果题目中要求对结果进行排序,请使用TreeMap

      键:表示要统计的内容
      值:表示次数
package com.zzu.TreeMap;

import java.util.StringJoiner;
import java.util.TreeMap;

public class Demo3 {
    
    
    public static void main(String[] args) {
    
    
        /* 需求:
        字符串“aababcabcdabcde”
        请统计字符串中每一个字符出现的次数,并按照以下格式输出
        输出结果:
        a(5)b(4)c(3)d(2)e(1)

            新的统计思想:利用map集合进行统计

          如果题目中没有要求对结果进行排序,默认使用HashMap
          如果题目中要求对结果进行排序,请使用TreeMap

          键:表示要统计的内容
          值:表示次数

        */


        //1.定义字符串
        String s = "aababcabcdabcde";

        //2.创建集合
        TreeMap<Character,Integer> tm = new TreeMap<>();

        //3.遍历字符串得到里面的每一个字符
        for (int i = 0; i < s.length(); i++) {
    
    
            char c = s.charAt(i);
            //拿着c到集合中判断是否存在
            //存在,表示当前字符又出现了一次
            //不存在,表示当前字符是第一次出现
            if(tm.containsKey(c)){
    
    
                //存在
                //先把已经出现的次数拿出来
                int count = tm.get(c);
                //当前字符又出现了一次
                count++;
                //把自增之后的结果再添加到集合当中
                tm.put(c,count);
            }else{
    
    
                //不存在
                tm.put(c,1);
            }
        }
		System.out.println(tm);
		
        //4.遍历集合,并按照指定的格式进行拼接
        // a(5)b(4)c(3)d(2)e(1)
        //两种拼接方式
        //4.1 StringBuilder
        StringBuilder sb = new StringBuilder();
        tm.forEach((key, value)->sb.append(key).append("(").append(value).append(")"));
        System.out.println("StringBuilder:"+sb);

        //4.2 StringJoiner
        StringJoiner sj = new StringJoiner("","","");
        tm.forEach((key, value)->sj.add(key + "").add("(").add(value + "").add(")"));
        System.out.println("StringJoiner:"+sj);
    }
}

{
    
    a=5, b=4, c=3, d=2, e=1}
StringBuilder:a(5)b(4)c(3)d(2)e(1)
StringJoiner:a(5)b(4)c(3)d(2)e(1)

Summarize

HashMap source code analysis

1.看源码之前需要了解的一些内容

Node<K,V>[] table   哈希表结构中数组的名字

DEFAULT_INITIAL_CAPACITY:   数组默认长度16

DEFAULT_LOAD_FACTOR:        默认加载因子0.75



HashMap里面每一个对象包含以下内容:
1.1 链表中的键值对对象
    包含:  
			int hash;         //键的哈希值
            final K key;      //键
            V value;          //值
            Node<K,V> next;   //下一个节点的地址值
			
			
1.2 红黑树中的键值对对象
	包含:
			int hash;         		//键的哈希值
            final K key;      		//键
            V value;         	 	//值
            TreeNode<K,V> parent;  	//父节点的地址值
			TreeNode<K,V> left;		//左子节点的地址值
			TreeNode<K,V> right;	//右子节点的地址值
			boolean red;			//节点的颜色
					


2.添加元素
HashMap<String,Integer> hm = new HashMap<>();
hm.put("aaa" , 111);
hm.put("bbb" , 222);
hm.put("ccc" , 333);
hm.put("ddd" , 444);
hm.put("eee" , 555);

添加元素的时候至少考虑三种情况:
2.1数组位置为null
2.2数组位置不为null,键不重复,挂在下面形成链表或者红黑树
2.3数组位置不为null,键重复,元素覆盖



//参数一:键
//参数二:值

//返回值:被覆盖元素的值,如果没有覆盖,返回null
public V put(K key, V value) {
    
    
    return putVal(hash(key), key, value, false, true);
}


//利用键计算出对应的哈希值,再把哈希值进行一些额外的处理
//简单理解:返回值就是返回键的哈希值
static final int hash(Object key) {
    
    
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

//参数一:键的哈希值
//参数二:键
//参数三:值
//参数四:如果键重复了是否保留
//		   true,表示老元素的值保留,不会覆盖
//		   false,表示老元素的值不保留,会进行覆盖
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
    
    
	    //定义一个局部变量,用来记录哈希表中数组的地址值。
        Node<K,V>[] tab;
		
		//临时的第三方变量,用来记录键值对对象的地址值
        Node<K,V> p;
        
		//表示当前数组的长度
		int n;
		
		//表示索引
        int i;
		
		//把哈希表中数组的地址值,赋值给局部变量tab
		tab = table;

        if (tab == null || (n = tab.length) == 0){
    
    
			//1.如果当前是第一次添加数据,底层会创建一个默认长度为16,加载因子为0.75的数组
			//2.如果不是第一次添加数据,会看数组中的元素是否达到了扩容的条件
			//如果没有达到扩容条件,底层不会做任何操作
			//如果达到了扩容条件,底层会把数组扩容为原先的两倍,并把数据全部转移到新的哈希表中
			tab = resize();
			//表示把当前数组的长度赋值给n
            n = tab.length;
        }

		//拿着数组的长度跟键的哈希值进行计算,计算出当前键值对对象,在数组中应存入的位置
		i = (n - 1) & hash;//index
		//获取数组中对应元素的数据
		p = tab[i];
		
		
        if (p == null){
    
    
			//底层会创建一个键值对对象,直接放到数组当中
            tab[i] = newNode(hash, key, value, null);
        }else {
    
    
            Node<K,V> e;
            K k;
			
			//等号的左边:数组中键值对的哈希值
			//等号的右边:当前要添加键值对的哈希值
			//如果键不一样,此时返回false
			//如果键一样,返回true
			boolean b1 = p.hash == hash;
			
            if (b1 && ((k = p.key) == key || (key != null && key.equals(k)))){
    
    
                e = p;
            } else if (p instanceof TreeNode){
    
    
				//判断数组中获取出来的键值对是不是红黑树中的节点
				//如果是,则调用方法putTreeVal,把当前的节点按照红黑树的规则添加到树当中。
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            } else {
    
    
				//如果从数组中获取出来的键值对不是红黑树中的节点
				//表示此时下面挂的是链表
                for (int binCount = 0; ; ++binCount) {
    
    
                    if ((e = p.next) == null) {
    
    
						//此时就会创建一个新的节点,挂在下面形成链表
                        p.next = newNode(hash, key, value, null);
						//判断当前链表长度是否超过8,如果超过8,就会调用方法treeifyBin
						//treeifyBin方法的底层还会继续判断
						//判断数组的长度是否大于等于64
						//如果同时满足这两个条件,就会把这个链表转成红黑树
                        if (binCount >= TREEIFY_THRESHOLD - 1)
                            treeifyBin(tab, hash);
                        break;
                    }
					//e:			  0x0044  ddd  444
					//要添加的元素: 0x0055   ddd   555
					//如果哈希值一样,就会调用equals方法比较内部的属性值是否相同
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))){
    
    
						 break;
					}

                    p = e;
                }
            }
			
			//如果e为null,表示当前不需要覆盖任何元素
			//如果e不为null,表示当前的键是一样的,值会被覆盖
			//e:0x0044  ddd  555
			//要添加的元素: 0x0055   ddd   555
            if (e != null) {
    
    
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null){
    
    
					
					//等号的右边:当前要添加的值
					//等号的左边:0x0044的值
					e.value = value;
				}
                afterNodeAccess(e);
                return oldValue;
            }
        }
		
        //threshold:记录的就是数组的长度 * 0.75,哈希表的扩容时机  16 * 0.75 = 12
        if (++size > threshold){
    
    
			 resize();
		}
        
		//表示当前没有覆盖任何元素,返回null
        return null;
    }
	

TreeMap source code analysis

1.TreeMap中每一个节点的内部属性
K key;					//键
V value;				//值
Entry<K,V> left;		//左子节点
Entry<K,V> right;		//右子节点
Entry<K,V> parent;		//父节点
boolean color;			//节点的颜色




2.TreeMap类中中要知道的一些成员变量
public class TreeMap<K,V>{
    
    
   
    //比较器对象
    private final Comparator<? super K> comparator;

	//根节点
    private transient Entry<K,V> root;

	//集合的长度
    private transient int size = 0;

   

3.空参构造
	//空参构造就是没有传递比较器对象
	 public TreeMap() {
    
    
        comparator = null;
    }
	
	
	
4.带参构造
	//带参构造就是传递了比较器对象。
	public TreeMap(Comparator<? super K> comparator) {
    
    
        this.comparator = comparator;
    }
	
	
5.添加元素
	public V put(K key, V value) {
    
    
        return put(key, value, true);
    }

参数一:键
参数二:值
参数三:当键重复的时候,是否需要覆盖值
		true:覆盖
		false:不覆盖
		
	private V put(K key, V value, boolean replaceOld) {
    
    
		//获取根节点的地址值,赋值给局部变量t
        Entry<K,V> t = root;
		//判断根节点是否为null
		//如果为null,表示当前是第一次添加,会把当前要添加的元素,当做根节点
		//如果不为null,表示当前不是第一次添加,跳过这个判断继续执行下面的代码
        if (t == null) {
    
    
			//方法的底层,会创建一个Entry对象,把他当做根节点
            addEntryToEmptyMap(key, value);
			//表示此时没有覆盖任何的元素
            return null;
        }
		//表示两个元素的键比较之后的结果
        int cmp;
		//表示当前要添加节点的父节点
        Entry<K,V> parent;
		
		//表示当前的比较规则
		//如果我们是采取默认的自然排序,那么此时comparator记录的是null,cpr记录的也是null
		//如果我们是采取比较去排序方式,那么此时comparator记录的是就是比较器
        Comparator<? super K> cpr = comparator;
		//表示判断当前是否有比较器对象
		//如果传递了比较器对象,就执行if里面的代码,此时以比较器的规则为准
		//如果没有传递比较器对象,就执行else里面的代码,此时以自然排序的规则为准
        if (cpr != null) {
    
    
            do {
    
    
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else {
    
    
                    V oldValue = t.value;
                    if (replaceOld || oldValue == null) {
    
    
                        t.value = value;
                    }
                    return oldValue;
                }
            } while (t != null);
        } else {
    
    
			//把键进行强转,强转成Comparable类型的
			//要求:键必须要实现Comparable接口,如果没有实现这个接口
			//此时在强转的时候,就会报错。
            Comparable<? super K> k = (Comparable<? super K>) key;
            do {
    
    
				//把根节点当做当前节点的父节点
                parent = t;
				//调用compareTo方法,比较根节点和当前要添加节点的大小关系
                cmp = k.compareTo(t.key);
				
                if (cmp < 0)
					//如果比较的结果为负数
					//那么继续到根节点的左边去找
                    t = t.left;
                else if (cmp > 0)
					//如果比较的结果为正数
					//那么继续到根节点的右边去找
                    t = t.right;
                else {
    
    
					//如果比较的结果为0,会覆盖
                    V oldValue = t.value;
                    if (replaceOld || oldValue == null) {
    
    
                        t.value = value;
                    }
                    return oldValue;
                }
            } while (t != null);
        }
		//就会把当前节点按照指定的规则进行添加
        addEntry(key, value, parent, cmp < 0);
        return null;
    }	
	
	
	
	 private void addEntry(K key, V value, Entry<K, V> parent, boolean addToLeft) {
    
    
        Entry<K,V> e = new Entry<>(key, value, parent);
        if (addToLeft)
            parent.left = e;
        else
            parent.right = e;
		//添加完毕之后,需要按照红黑树的规则进行调整
        fixAfterInsertion(e);
        size++;
        modCount++;
    }
	
	
	
	private void fixAfterInsertion(Entry<K,V> x) {
    
    
		//因为红黑树的节点默认就是红色的
        x.color = RED;

		//按照红黑规则进行调整
		
		//parentOf:获取x的父节点
		//parentOf(parentOf(x)):获取x的爷爷节点
		//leftOf:获取左子节点
        while (x != null && x != root && x.parent.color == RED) {
    
    
			
			
			//判断当前节点的父节点是爷爷节点的左子节点还是右子节点
			//目的:为了获取当前节点的叔叔节点
            if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
    
    
				//表示当前节点的父节点是爷爷节点的左子节点
				//那么下面就可以用rightOf获取到当前节点的叔叔节点
                Entry<K,V> y = rightOf(parentOf(parentOf(x)));
                if (colorOf(y) == RED) {
    
    
					//叔叔节点为红色的处理方案
					
					//把父节点设置为黑色
                    setColor(parentOf(x), BLACK);
					//把叔叔节点设置为黑色
                    setColor(y, BLACK);
					//把爷爷节点设置为红色
                    setColor(parentOf(parentOf(x)), RED);
					
					//把爷爷节点设置为当前节点
                    x = parentOf(parentOf(x));
                } else {
    
    
					
					//叔叔节点为黑色的处理方案
					
					
					//表示判断当前节点是否为父节点的右子节点
                    if (x == rightOf(parentOf(x))) {
    
    
						
						//表示当前节点是父节点的右子节点
                        x = parentOf(x);
						//左旋
                        rotateLeft(x);
                    }
                    setColor(parentOf(x), BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    rotateRight(parentOf(parentOf(x)));
                }
            } else {
    
    
				//表示当前节点的父节点是爷爷节点的右子节点
				//那么下面就可以用leftOf获取到当前节点的叔叔节点
                Entry<K,V> y = leftOf(parentOf(parentOf(x)));
                if (colorOf(y) == RED) {
    
    
                    setColor(parentOf(x), BLACK);
                    setColor(y, BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    x = parentOf(parentOf(x));
                } else {
    
    
                    if (x == leftOf(parentOf(x))) {
    
    
                        x = parentOf(x);
                        rotateRight(x);
                    }
                    setColor(parentOf(x), BLACK);
                    setColor(parentOf(parentOf(x)), RED);
                    rotateLeft(parentOf(parentOf(x)));
                }
            }
        }
		
		//把根节点设置为黑色
        root.color = BLACK;
    }
	
	
	
	
	
	
	
6.课堂思考问题:
6.1TreeMap添加元素的时候,键是否需要重写hashCode和equals方法?
此时是不需要重写的。


6.2HashMap是哈希表结构的,JDK8开始由数组,链表,红黑树组成的。
既然有红黑树,HashMap的键是否需要实现Compareable接口或者传递比较器对象呢?
不需要的。
因为在HashMap的底层,默认是利用哈希值的大小关系来创建红黑树的




6.3TreeMap和HashMap谁的效率更高?
如果是最坏情况,添加了8个元素,这8个元素形成了链表,此时TreeMap的效率要更高
但是这种情况出现的几率非常的少。
一般而言,还是HashMap的效率要更高。



6.4你觉得在Map集合中,java会提供一个如果键重复了,不会覆盖的put方法呢?
此时putIfAbsent本身不重要。
传递一个思想:
	代码中的逻辑都有两面性,如果我们只知道了其中的A面,而且代码中还发现了有变量可以控制两面性的发生。
	那么该逻辑一定会有B面。
	
	习惯:
		boolean类型的变量控制,一般只有AB两面,因为boolean只有两个值
		int类型的变量控制,一般至少有三面,因为int可以取多个值。
		



6.5三种双列集合,以后如何选择?
	HashMap LinkedHashMap TreeMap
	
	默认:HashMap(效率最高)
	如果要保证存取有序:LinkedHashMap
	如果要进行排序:TreeMap


Guess you like

Origin blog.csdn.net/bigBbug/article/details/130244690