Download Set_advanced_project/Map_module/src/HashMap_package1/HashMap_demo.java from zxy0307/Java: direct link, hf CLI and curl.
- Browser
- Download file 1.82 kB
-
https://huggingface.co/zxy0307/Java/resolve/main/Set_advanced_project/Map_module/src/HashMap_package1/HashMap_demo.java
- Command line
-
hf download hf://zxy0307/Java/Set_advanced_project/Map_module/src/HashMap_package1/HashMap_demo.java
-
curl -L -o HashMap_demo.java https://huggingface.co/zxy0307/Java/resolve/main/Set_advanced_project/Map_module/src/HashMap_package1/HashMap_demo.java
1.82 kB
| package HashMap_package1; | |
| import java.util.HashMap; | |
| import java.util.Map; | |
| import java.util.Set; | |
| import java.util.function.BiConsumer; | |
| public class HashMap_demo { | |
| public static void main(String[] args) { | |
| /* | |
| 需求:创建一个HashMap集合,键是学生对象(Student),值是籍贯(String)。 | |
| 存储三个键值对元素,并遍历 | |
| 要求:同姓名,同年龄认为是同一个学生 | |
| 核心点: | |
| HashMap的键位置如果存储的是自定义对象,需要重写hashCode和equals方法。 | |
| */ | |
| //1、创建HashMap的对象 | |
| HashMap<Student, String> hm = new HashMap<>(); | |
| //2、创建三个学生对象 | |
| Student s1 = new Student("zhangsan", 23); | |
| Student s2 = new Student("lisi", 24); | |
| Student s3 = new Student("wangwu", 25); | |
| //3、添加元素 | |
| hm.put(s1, "江苏"); | |
| hm.put(s2, "浙江"); | |
| hm.put(s3, "福建"); | |
| //4、遍历集合 | |
| Set<Student> keys = hm.keySet(); | |
| for (Student key : keys) { | |
| String value = hm.get(key); | |
| System.out.println(key + "=" + value); | |
| } | |
| System.out.println("----------------------------------------"); | |
| Set<Map.Entry<Student, String>> entries = hm.entrySet(); | |
| for (Map.Entry<Student, String> entry : entries) { | |
| Student key = entry.getKey(); | |
| String value = entry.getValue(); | |
| System.out.println(key + "=" + value); | |
| } | |
| System.out.println("----------------------------------------"); | |
| hm.forEach(new BiConsumer<Student, String>() { | |
| public void accept(Student key, String value) { | |
| System.out.println(key + "=" + value); | |
| } | |
| }); | |
| } | |
| } | |