HashMap集合存储学生对象并遍历
package package5;
//创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
//创建HashMap集合对象
HashMap<String,Student> hashMap =new HashMap<>();
//创建学生对象
Student s1 =new Student("张三",21);
Student s2 =new Student("李四",22);
Student s3 =new Student("王五",23);
//将学生对象存储到集合中
hashMap.put("h001",s1);
hashMap.put("h002",s2);
hashMap.put("h003",s3);
//遍历集合方式1:键找值
//获取所有的键的集合
Set<String> keySet = hashMap.keySet();
for(String key:keySet){
Student value = hashMap.get(key);
System.out.println(key+","+value.getName()+", "+value.getAge());
}
//方法2:键值对对象找键和值
//获取所有键值对对象的集合
Set<Map.Entry<String, Student>> entries = hashMap.entrySet();
for(Map.Entry<String, Student> s:entries){
String key = s.getKey();
Student value = s.getValue();
System.out.println(key+","+value.getName()+", "+value.getAge());
}
}
}
运行结果:
h001,张三, 21
h002,李四, 22
h003,王五, 23

浙公网安备 33010602011771号