s-day04--Map集合存储自定义对象

This commit is contained in:
xx
2026-10-15 13:46:20 +08:00
parent 79cf925b27
commit ed3c312e1f
2 changed files with 71 additions and 0 deletions
@@ -0,0 +1,33 @@
package com.inmind.map01;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/*
5.Map集合存储自定义对象
需求:每位学生(姓名,年龄)都有自己的家庭住址,我要把学生对象和居住城市存储到Map集合中,学生作为键key,居住城市作为值
注意:学生姓名和年龄如果相同看作同一个学生
哈希:通过hashCode,equals实现去重
总结:
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) {
Map<Student, String> map = new HashMap<>();
map.put(new Student("张三1", 19), "上海");
map.put(new Student("张三2", 18), "苏州");
map.put(new Student("张三3", 21), "常州");
map.put(new Student("张三1", 19), "上海");
System.out.println(map);
HashSet<String> hashSet = new HashSet<>();
hashSet.add("");
}
}
+38
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 +
'}';
}
//要实现去重,必定要重写hashCode,equals方法
@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;
}
}