package com.it02;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
//创建集合对象
HashMap<String, Student> hm = new HashMap<>();
//创建学生对象
Student s1 = new Student("小王", 23);
Student s2 = new Student("大王", 25);
Student s3 = new Student("王总", 29);
//添加学生对象到集合中
hm.put("1", s1);
hm.put("2", s2);
hm.put("3", s3);
//1、遍历集合:方式一:键找值
Set<String> keySet = hm.keySet();
for (String key : keySet) {
Student value = hm.get(key);
System.out.println(key + "," +
value.getName() + "," + value.getAge());
}
System.out.println("=============================");
//2、遍历集合:方式二:键值对对象找键和值
Set<Map.Entry<String,Student>> entrySet = hm.entrySet();
for (Map.Entry<String,Student> me:entrySet) {
String key = me.getKey();
Student value = me.getValue();
System.out.println(key + "," +
value.getName() + "," + value.getAge());
}
}
}
案例——HashMap集合存储学生对象并遍历(Map集合的两种遍历方式)
最新推荐文章于 2023-06-12 15:52:36 发布