创建学生类对象
public class Student {
private String name;
public int age ;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
测试类对象
public class MapDemo {
public static void main(String[] args) {
/**
* 需求:创建一个HashMap集合,键是学号(String),值是学生对象(String)。
* 存储三个键值对,并遍历
* 思路:
* 1.定义学生类
* 2.创建HashMap集合对象
* 3.创建学生对象
* 4.把学生添加到集合
* 5.遍历集合:方式1:键找值,方式2:键值对对象找键和值
*/
//创建HashMap集合对象
HashMap<String, Student> hm = new HashMap<>();
//创建学生对象
Student s1 = new Student("林青霞", 30);
Student s2 = new Student("张曼玉", 35);
Student s3 = new Student("王祖贤", 33);
//把学生添加到集合
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());
}
}
}
运行结果