//学生类
//注意:需要重写两个方法hashCode()和equals()
package package6;
import java.util.Objects;
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 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 package6;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
//创建HashMap集合对象
HashMap<Student, String> hashMap = new HashMap<>();
//创建学生对象
Student s1 = new Student("张三", 21);
Student s2 = new Student("李四", 22);
Student s3 = new Student("王五", 23);
Student s4 = new Student("王五", 23);
//将学生对象存储到集合中
hashMap.put(s1,"安庆");
hashMap.put(s2,"南京");
hashMap.put(s3,"合肥");
hashMap.put(s4,"芜湖");
//遍历集合
Set<Map.Entry<Student, String>> entrySet = hashMap.entrySet();
for(Map.Entry<Student, String> me:entrySet){
Student key = me.getKey();
String value = me.getValue();
System.out.println(key.getName()+", "+key.getAge()+", "+value);
}
}
}
运行结果
张三, 21, 安庆
李四, 22, 南京
王五, 23, 芜湖
标签:HashMap,对象,age,String,键值,Student,public,name
From: https://www.cnblogs.com/knlf/p/16800228.html