HashMap集合存储学生对象并遍历
Posted iuiu啊
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HashMap集合存储学生对象并遍历相关的知识,希望对你有一定的参考价值。
需求:创建一个HashMap集合,键是学生对象(Student),值是居住地。存储多个键值对元素,并遍历。
要求保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象
思路:
定义学生类
创建HashMap集合对象
创建学生对象
把学生添加到集合
遍历集合
在学生类中重写两个方法
hashCode()
equals()
代码实现:
编写Student类
package com.aynu3;
import java.util.Objects;
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;
@Override
public boolean equals(Object o)
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return Objects.equals(name, student.name);
@Override
public int hashCode()
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
package com.aynu3;
import java.util.HashMap;
import java.util.Set;
public class HashMapDemo
public static void main(String[] args)
//创建HashMap集合对象
HashMap<Student,String> hm=new HashMap<Student,String>();
//创建学生对象
Student s1=new Student("林青霞",30);
Student s2=new Student("张曼玉",35);
Student s3=new Student("王祖贤",33);
Student s4=new Student("王祖贤",33);
//把学生添加到集合
hm.put(s1,"西安");
hm.put(s2,"武汉");
hm.put(s3,"洛阳");
hm.put(s4,"北京");
//遍历集合
Set<Student> keySet = hm.keySet();
for (Student key:keySet)
String value = hm.get(key);
System.out.println(key.getName() + "," + key.getAge()+","+value);
运行结果:
王祖贤,33,北京
张曼玉,35,武汉
林青霞,30,西安
JavaSE-14.2.2案例-List集合存储学生对象并遍历
package day5.lesson2; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /* 2.3 案例-List集合存储学生对象并遍历 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合 */ public class ListDemo2 { public static void main(String[] args) { List<Student> list = new ArrayList<>(); Student s1 = new Student("sam", 12); Student s2 = new Student("amy", 11); Student s3 = new Student("tom", 12); list.add(s1); list.add(s2); list.add(s3); //遍历方式1 Iterator<Student> it = list.iterator(); while (it.hasNext()){ Student s = it.next(); System.out.println(s.getName() + "," + s.getAge()); } //遍历方式2 for(int i=0; i<list.size(); i++){ Student stu = list.get(i); System.out.println(stu.getName() + "," + stu.getAge()); } } }
package day5.lesson2; public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
以上是关于HashMap集合存储学生对象并遍历的主要内容,如果未能解决你的问题,请参考以下文章
JavaSE-14.2.2案例-List集合存储学生对象并遍历
JAVA-初步认识-常用对象API(集合框架-Map集合-存储自定义对象)