本文已参与「新人创作礼」活动,一起开启掘金创作之路。
首先写入三个学生,学生的唯一标识是学号。
import java.util.HashMap;
public class AADemo_2 {
public static void main(String[] args) {
HashMap<Student,String> map = new HashMap<>();
Student student1 = new Student("1号",11,202201);
Student student2 = new Student("2号",12,202202);
Student student3 = new Student("3号",13,202203);
map.put(student1,"一本");
map.put(student2,"二本");
map.put(student3,"大专");
map.forEach((key,value) -> System.out.println(key+value));
}
}
class Student{
String name;
Integer age;
Integer id;
public Student(String name, Integer age, Integer id) {
this.name = name;
this.age = age;
this.id = id;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + ''' +
", age=" + age +
", id=" + id +
'}';
}
}
输出如下:
Student{name='2号', age=12, id=202202}二本
Student{name='3号', age=13, id=202203}大专
Student{name='1号', age=11, id=202201}一本
现在因为技术原因导致同一个学生被写入了两次
public class AADemo_2 {
public static void main(String[] args) {
HashMap<Student,String> map = new HashMap<>();
Student student1 = new Student("1号",11,202201);
Student student2 = new Student("2号",12,202202);
Student student3 = new Student("3号",13,202203);
Student student4 = new Student("3号",13,202203);
map.put(student1,"一本");
map.put(student2,"二本");
map.put(student3,"大专");
map.put(student4,"大专");
map.forEach((key,value) -> System.out.println(key+value));
}
}
Student{name='2号', age=12, id=202202}二本
Student{name='3号', age=13, id=202203}大专
Student{name='1号', age=11, id=202201}一本
Student{name='3号', age=13, id=202203}大专
领导说这种情况他不能容忍,要求程序员修改代码,否则就要扣工资 程序员想来想去,有了一个点子,重写hashcode和equals方法
package aa;
import java.util.HashMap;
public class AADemo_2 {
public static void main(String[] args) {
Object a = new Object();
HashMap<Student,String> map = new HashMap<>();
Student student1 = new Student("1号",11,202201);
Student student2 = new Student("2号",12,202202);
Student student3 = new Student("3号",13,202203);
Student student4 = new Student("3号",13,202203);
map.put(student1,"一本");
map.put(student2,"二本");
map.put(student3,"大专");
map.put(student4,"大专");
map.forEach((key,value) -> System.out.println(key+value));
}
}
class Student{
String name;
Integer age;
Integer id;
public Student(String name, Integer age, Integer id) {
this.name = name;
this.age = age;
this.id = id;
}
@Override
public int hashCode() {
if (this == null || !(this instanceof Student)){
return 0;
}
int code = this.name.hashCode()+age+id;
return code;
}
@Override
public boolean equals(Object obj) {
if (obj == null || this == null || !(obj instanceof Student)){
return false;
}
boolean flag = false;
flag = this.hashCode() == obj.hashCode()?true:false;
return flag;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + ''' +
", age=" + age +
", id=" + id +
'}';
}
}
运行结果:
Student{name='2号', age=12, id=202202}二本
Student{name='1号', age=11, id=202201}一本
Student{name='3号', age=13, id=202203}大专
程序员把代码发给领导看了之后,领导非常满意,并决定不扣程序员的工资
|