需求:
创建一个HashMap集合,键是学生对象(Students),值是(String)
存储三个键值对元素,并遍历
要求:同姓名,同年龄认为是同一个学生
代码:
学生类
import java.util.Objects;
public class Students {
private String name;
private int age;
public Students() {
}
public Students(String name, int age) {
this.name = name;
this.age = age;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
* @param 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;
Students students = (Students) o;
return age == students.age && Objects.equals(name, students.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public String toString() {
return name+"="+age ;
}
}
重写hashCode方法和equals方法确定键的唯一性
测试类:
import java.util.HashMap;
import java.util.function.BiConsumer;
public class Main {
public static void main(String[] args) {
HashMap<Students, String> map = new HashMap<>();
Students s = new Students("小航",14);
Students s2 = new Students("小章",14);
Students s3= new Students("小黑",14);
Students s4= new Students("小黑",14);
map.put(s,"广东");
map.put(s2,"广东");
map.put(s3,"广东");
map.put(s4,"广东");
//HashMap特点不重复,重写HashCode方法和equals方法哈希值是唯一的
//System.out.println(s3.hashCode());哈希值23909229
//System.out.println(s4.hashCode());哈希值23909229
map.forEach(new BiConsumer<Students, String>() {
@Override
public void accept(Students Key, String Value) {
System.out.println(Key+"="+Value);
}
});
}
}
结果:
小黑=14=广东
小章=14=广东
小航=14=广东