262 hashmap集合练习之:键是String
【需求】
创建一个HashMap集合,键是学号(String),值是学生对象(Student)。
存储3个集合元素
遍历集合
【思路】
1. 定义Student类
2. 创建HashMap集合,键值对是String,Student
3. 创建Student对象
4. 添加3个元素
5. 遍历集合
--------------------------------------------------------------
package e262;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String, Student262> jihe262 = new HashMap<String, Student262>();
Student262 ss1 = new Student262("TRACY", 33);
Student262 ss2 = new Student262("BEN", 70);
Student262 ss3 = new Student262("CECILIA", 23);
jihe262.put("s2021", ss1);
jihe262.put("s2022", ss2);
jihe262.put("s2023", ss3);
Set<String> jianjihe = jihe262.keySet();
for (String jian : jianjihe) {
Student262 zhi = jihe262.get(jian);
System.out.println(jian + "," + zhi.getName() + "," + zhi.getAge());
}
System.out.println("--------above is method 1,below is method 2--------");
Set<Map.Entry<String, Student262>> entrySet = jihe262.entrySet();
for (Map.Entry<String, Student262> meme : entrySet) {
String jian = meme.getKey();
Student262 zhi = meme.getValue();
System.out.println(jian + "," + zhi.getName() + "," + zhi.getAge());
//ctrl alt l
}
}
}
--------------------------------------------------------------
s2021,TRACY,33
s2022,BEN,70
s2023,CECILIA,23
--------above is method 1,below is method 2--------
s2021,TRACY,33
s2022,BEN,70
s2023,CECILIA,23