创建学生类对象
public class Student {
private String name;
public 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;
}
}
测试类对象
public class MapDemo {
public static void main(String[] args) {
/**
* 需求:
* 创建一个HashMap集合,键是学生对象(Strudent),值是居住地(String),存储多个键值对元素并遍历
* 要求保证键的唯一性,如果学生对象的成员变量值相同,我们就认为是同一个人
*
* 思路:
* 1.定义学生类
* 2.创建HashMap集合对象
* 3.创建学生对象
* 4.把学生添加到集合
* 5.遍历集合
* 6.在学生类中重写两个方法
* hashCode()
* equals()
*/
//创建HashMap集合对象
HashMap<Student, String> hm = new HashMap<>();
//创建学生对象
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);
}
}
}
测试结果
可以看到S4将S3覆盖了,因为s3和s4key相同,通过学生类对象中hashCode和equels方法使得键相同时值覆盖。