需求:创建一个HashMap集合,键是学生对象(Student),值是居住地(String)。存储多个键值对元素,并遍历。要求保证键的唯一性:如果学生对象的成员变量值相同,认为是同一个对象
先建立一个学生类
package ysy14;
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;
}
//保证键唯一性,在学生类中重写hashCode()和equals()方法
//名称一样,后写的值会覆盖掉
@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 ysy14;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
//创建集合对象,键是Student,值是String
Map<Student, String> map = new HashMap<Student, String>();
//创建学生对象
Student s1 = new Student("小鱼", 17);
Student s2 = new Student("小金", 21);
Student s3 = new Student("小鸟", 14);
Student s4 = new Student("小鸟", 14);
//添加学生到集合
map.put(s1, "淮安");
map.put(s2, "南京");
map.put(s3, "上海");
map.put(s4, "香港");
//遍历集合:键找值
Set<Student> keySet = map.keySet();
for (Student key : keySet) {
String value = map.get(key);
System.out.println(key.getName() + "," + key.getAge() + "," + value);
}
}
}