案例:HashMap集合存储学生对象并遍历
-
需求:创建一个HashMap集合,键是学生对象,值是居住地,存储对个键值对元素,并遍历,要求保证键的唯一性,如果学生对象的成员变量值相同,我们就认为同一对象
-
思路:
- 定义学生类
- 创建HashMap集合
- 创建学生对象
- 把学生对象添加到集合中
- 遍历集合:
方式1:键找值
方式2:键值对对象找键和值 - 在学生类中重写方法
hashCode()
equals()
- 注意:hashMap底层结构是哈希值,重写相应的方法可以保键的唯一性(注意是键的唯一性)
以代码的内容形式展开
Student类(注意有重写方法)
package Demo;
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;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
Demo类
package Demo;
import java.util.*;
public class Demo {
public static void main(String[] args) {
//创建HashMap()
HashMap<Student, String> s = new HashMap<>();
//建立集合
Student s1 = new Student("沸羊羊",21);
Student s2 = new Student("喜羊羊",23);
Student s3 = new Student("懒洋洋",19);
Student s4 = new Student("美羊羊",27);
Student s5 = new Student("美羊羊",27);
//添加元素
s.put(s1,"西安");
s.put(s2,"汉中");
s.put(s3,"榆林");
s.put(s4,"咸阳");
s.put(s5,"咸阳");
//遍历集合
//1 根据键所找值
Set<Student> students = s.keySet();
for (Student x:students) {
String sss = s.get(x);
System.out.println(x.getName()+","+x.getAge()+","+sss);
}
System.out.println("================");
//2 根据键对所找值
Set<Map.Entry<Student, String>> entries = s.entrySet();
for (Map.Entry<Student, String> x:entries) {
Student key = x.getKey();
String value = x.getValue();
System.out.println(key.getName()+ key.getAge()+","+value);
}
}
}
输出的内容
喜羊羊,23,汉中
沸羊羊,21,西安
美羊羊,27,咸阳
懒洋洋,19,榆林
================
喜羊羊23,汉中
沸羊羊21,西安
美羊羊27,咸阳
懒洋洋19,榆林