代码奉上
package algorithm.map;
import java.util.Objects;
/**
* @author xiaowang
* @creat 2024/6/8 22:18
* @Description Java Lotus
*/
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 String toString() {
return "Student{" +
"name='" + name + '\'' +
", 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);
}
}
package algorithm.map;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* @author xiaowang
* @creat 2024/6/8 22:19
* @Description Java Lotus
*/
public class MapDemo5 {
public static void main(String[] args) {
HashMap<Student,String>stringHashMap=new HashMap<>();
stringHashMap.put(new Student("张三",23),"北京");
stringHashMap.put(new Student("李四",24),"上海");
stringHashMap.put(new Student("张三",23),"北京");
Set<Student>keys=stringHashMap.keySet();
for (Student key : keys) {
System.out.println(key+"----"+stringHashMap.get(key));
}
}
}