需求:创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历

1.定义学生类

2.创建HashMap集合对象

3.创建学生对象

4.把学生添加到集合

5.遍历集合

    方式1:键值找

    方式2:键值对对象找键和值

package com.itheima_25;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
需求:创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历
1.定义学生类
2.创建HashMap集合对象
3.创建学生对象
4.把学生添加到集合
5.遍历集合
方式1:键值找
方式2:键值对对象找键和值
*/
public class HashMapDemo {
public static void main(String[] args) {
//创建HashMap集合对象
HashMap<String,Student> hm = new HashMap<String,Student>();
//创建学生对象
Student s1 = new Student("张三",20);
Student s2 = new Student("李四",22);
Student s3 = new Student("王五",23);
Student s4 = new Student("赵六",24);

//把学生添加到集合
hm.put("wx001",s1);
hm.put("wx002",s2);
hm.put("wx003",s3);
hm.put("wx004",s4);

//方式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>> entries = hm.entrySet();

for (Map.Entry<String, Student> entry:entries){
String key = entry.getKey();
Student value = entry.getValue();
System.out.println(key + "," + value.getName() + "," + value.getAge());
}

}
}
package com.itheima_25;

public class Student {
private String name;
private int age;


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;
}
}