package cn.itcast_02;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/*
* HashMap存储键和值。并遍历。
* 键:String 学号
* 值:Student (name,age)
*/
public class HashMapDemo2 {
public static void main(String[] args) {
// 创建集合对象
HashMap<String, Student> hm = new HashMap<String, Student>();
// 创建元素对象
Student s1 = new Student("李世民", 30);
Student s2 = new Student("朱元璋", 40);
Student s3 = new Student("武则天", 50);
// 添加元素
hm.put("it001", s1);
hm.put("it002", s2);
hm.put("it003", s3);
// 遍历
Set<String> set = hm.keySet();
for (String key : set) {
Student value = hm.get(key);
System.out.println(key + "***" + value.getName() + "***"
+ value.getAge());
}
// 遍历2
Set<Map.Entry<String, Student>> hmSet = hm.entrySet();
for (Map.Entry<String, Student> me : hmSet) {
String key = me.getKey();
Student value = me.getValue();
System.out.println(key + "***" + value.getName() + "***"
+ value.getAge());
}
}
}
|
|