image.png
    image.png
    image.png

    1. package com.itheima.d9_map_impl;
    2. import com.itheima.d1_set.Student;
    3. import java.util.HashMap;
    4. import java.util.Map;
    5. public class HashMapDemo1 {
    6. public static void main(String[] args) {
    7. // Map集合是根据键去除重复元素
    8. Map<Student,String> maps = new HashMap<>();
    9. // 创建三个学生对象放到 HashMap集合中
    10. Student s1 = new Student("无恙",20,'男');
    11. Student s2 = new Student("无恙",20,'男');
    12. Student s3 = new Student("周雄",20,'男');
    13. // 因为Student类里面重写了HashCode和equals方法,根据哈希值去重复
    14. maps.put(s1,"北京"); // 这个时候形参一样s1和s2,被当成同一个对象,去重复了
    15. maps.put(s2,"上海"); // s2,覆盖了s1
    16. maps.put(s3,"广州");
    17. System.out.println(maps); //{Student{name='无恙', age=20, sex=男}=上海, Student{name='周雄', age=20, sex=男}=广州}
    18. // 最终只会保留两个元素
    19. }
    20. }