进阶day04-Map集合存储自定义对象(要重写hashCode&equals)

This commit is contained in:
2026-02-03 10:51:45 +08:00
parent 2202c4d113
commit 77b9796f46
2 changed files with 71 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
package com.inmind.map01;
import java.util.HashMap;
import java.util.HashSet;
/*
练习每位学生姓名年龄都有自己的家庭住址。那么既然有对应关系则将学生对象和家庭住址存储到map集合中。
学生作为键, 家庭住址作为值。
注意:学生姓名相同并且年龄相同视为同一名学生。
总结:
1.hashMap存储自定义对象时,要实现去重,必须在自定义类中重写hashcode和equals
2.HashMap:底层是哈希表,它要实现去重,它跟hashcode和equals有关
3.HashSet底层就是HashMap.(查看源码),就是将Set中的数据作为map的键而值永远是同一个常量
*/
public class MapDemo04 {
public static void main(String[] args) {
//定义出一个键为Student值为String的双列集合
HashMap<Student, String> map = new HashMap<>();
map.put(new Student("张三", 18), "苏州");
map.put(new Student("李四", 19), "无锡");
map.put(new Student("王五", 20), "常州");
//业务上,我希望是王五从常州搬到了上海
map.put(new Student("王五", 20), "上海");
System.out.println(map);
HashSet<String> sets = new HashSet<>();
sets.add("1123");
}
}

View File

@@ -0,0 +1,38 @@
package com.inmind.map01;
import java.util.Objects;
public class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
//重写equals的目的为了让2个内容相同的对象看作是同一个
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
//重写hashCode的目的为了让相同内容的对象特征码对象的哈希值相同
@Override
public int hashCode() {
int result = Objects.hashCode(name);
result = 31 * result + age;
return result;
}
}