c语言sscanf函数的用法是什么
283
2022-10-14
Java案例之HashMap集合存储学生对象并遍历
一、需求:创建一个HashMap集合,键是学号(String),值是学生对象(Student),存储三个键值对元素,并遍历
分析:
1.定义学生类2.创建HashMap集合对象3.创建学生对象4把学生添加到集合中5.遍历集合
public class StudentDemo {
public static void main(String[] args) {
//创建Map集合对象
Map
//添加键值对
m.put("01",new Student("张三"));
m.put("04",new Student("赵六"));
m.put("02",new Student("李四"));
m.put("03",new Student("王五"));
//遍历集合
Set
//遍历
for (Map.Entry
//根据键值对对象获取值和key
String key=ss.getKey();
Student value=ss.getValue();
System.out.println(key+","+value.getName());
}
System.out.println("------------------------");
//方式二,通过键找值
Set
for (String key :m1){
Student student =m.get(key);
System.out.println(key+","+student.getName());
}
}
}
二、需求:创建一个HashMap集合,键是学生对象(Student),值是地址(String),存储三个键值对元素,并遍历分析:
1.定义学生类2.创建HashMap集合对象3.创建学生对象,并把学生对象当作键值添加到集合4把地址字符串添加到集合中5.为了保证数据的唯一性,需要在学生类中重写hashCode及equals方法6.遍历集合
public class StudentDemo {
public static void main(String[] args) {
//创建集合对象
Map
//添加键值对
m.put(new Student("张三",18),"上海");
m.put(new Student("李四",19),"北京");
m.put(new Student("王五",20),"上海");
m.put(new Student("王五",20),"海南");
//方式一
//获取所有键值对的集合
Set
//方式一、遍历
for (Map.Entry
//通过键值对获取对应的值与键
Student key=mm.getKey();
String value=mm.getValue();
System.out.println(key.getName()+","+key.getAge()+value);
}
System.out.println("---------------------------------");
//方式二
Set
for (Student s1:key){
String value=m.get(s1);
System.out.println(s1.getName()+","+s1.getAge()+","+value);
}
}
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~