集合之Map【HashMap】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.Lucky.Map;
 
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
 
 
/*
     HashMap:  1.底层结构是哈希表
               2.依赖hashCode以及equals方法保证键的唯一
               3.如果键储存的是“自定义对象”,就要重写hashCode方法以及equals方法
               4.如果值储存的是:自定义对象,就不用重写上面两个方法
 
 */
public class HashMap {
    public static void main(String[] args) {
        Map<Student,String> map=new java.util.HashMap<>();
 
        Student str1=new Student("唯一",22);
        Student str2=new Student("唯二",20);
        Student str3=new Student("唯三",22);
        Student str4=new Student("唯三",22);
 
        map.put(str1,"汉族");
        map.put(str2,"壮族");
        map.put(str3,"黎族");
        map.put(str4,"黎族");   //添加失败
 
      //  System.out.println(map);
 
        //
//        map.forEach(new BiConsumer<Student, String>() {
//            @Override
//            public void accept(Student student, String s) {
//                System.out.println(student);
//                System.out.println(s);
//            }
//        });
 
        map.forEach((stu,res)-> System.out.println(stu+":"+res));
 
 
        System.out.println("-----------------增强for循环-------------------");
        Set<Map.Entry<Student, String>> entries = map.entrySet();
        for (Map.Entry<Student, String> entry : entries) {
            System.out.println(entry.getKey()+":"+entry.getValue());
        }
 
        System.out.println("-----------------迭代器-------------------");
        Iterator<Map.Entry<Student, String>> iterator = entries.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
 
}

  材料:

  综合小练习:

  

posted @   唯易人生  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示