HashMap集合存储学生对象并遍历
需求:创建一个HashMap集合,键是学号(String),值是学生对象(Student),存储三个键值对元素,并遍历。
思路
- 定义一个学生类
- 创建HashMap集合对象
- 创建学生对象
- 把学生添加到集合
- 遍历集合(两种方式)
1 键找值
2 键值对对象找键和值
定义一个学生类(用Alt+Insert可直接生成)
package Test_10;
public class Student {
private String name;
private 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;
}
}
在这里插入代码片
另外一个类中的内容
package Test_10;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 题目:HashMap集合存储学生对象并遍历
* 需求:创建一个HashMap集合,键是学号(String),值是学生对象(Student),存储三个键值对元素,并遍历
*/
public class HashMapCase {
public static void main(String[] args) {
HashMap<String, Student> hm = new HashMap<String, Student>();
Student s1 = new Student("魏无羡", 25);
Student s2 = new Student("蓝忘机", 24);
Student s3 = new Student("魏婴", 22);
hm.put("001", s1);
hm.put("002", s2);
hm.put("003", s3);
//遍历集合1,键找值
Set<String> keySet = hm.keySet();
for (String key : keySet) {
Student s = hm.get(key);
System.out.println(key +","+ s.getName() + ", " + s.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());
}
}
}