s-day04Map集合存储自定义对象

This commit is contained in:
2026-08-03 10:17:30 +08:00
parent 3851e10a8f
commit 80a09fc057
2 changed files with 71 additions and 0 deletions
@@ -0,0 +1,35 @@
package com.inmind.map01;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/*
5.Map集合存储自定义对象
需求:每位学生(姓名,年龄)都有自己的家庭住址,我要把学生对象和居住城市存储到Map集合中,学生作为键key,居住城市作为值
注意:学生姓名和年龄如果相同看作同一个学生
哈希:通过hashCodeequals实现去重
总结:
1.hashMap存储自定义对象作为key时,要实现去重,必须在自定义类中重写hashCode,equals方法
2.HashMap:底层数据结构就是哈希表,它跟对象哈希值有关
3.HashSet 底层就是HashMap,HashMap<E,Object>,将set中的值作为map中的key,而map中值没有任何作用,就保存相同的数据
*/
public class MapDemo04 {
public static void main(String[] args) {
//学生作为键key,居住城市作为值创建双列集合
Map<Student, String> maps = new HashMap<>();
HashSet set = new HashSet();
set.add(1);
maps.put(new Student("小王1", 18), "南京");
maps.put(new Student("小王2", 19), "苏州");
maps.put(new Student("小王3", 17), "无锡");
maps.put(new Student("小王4", 18), "常州");
maps.put(new Student("小王1", 18), "上海");
System.out.println(maps);
System.out.println(maps.size());
}
}
+36
View File
@@ -0,0 +1,36 @@
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 +
'}';
}
@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);
}
@Override
public int hashCode() {
int result = Objects.hashCode(name);
result = 31 * result + age;
return result;
}
}