Back to tasksGet help with live coding in real time with Sobes Copilot
Junior — Senior
29
Правильное использование объектов‑ключей в HashMap
Task condition
В примере используется HashMap<Exam, String>, где в качестве ключей выступают экземпляры класса Exam. Необходимо реализовать корректный механизм сравнения объектов Exam, чтобы HashMap правильно обрабатывала повторяющиеся ключи.
import java.util.HashMap;
import java.util.Map;
public class JetbulbInterview {
public static void main(String[] args) {
Map<Exam, String> exams = new HashMap<>();
Exam examOne = new Exam(1, "04.07.2021", 10);
Exam examTwo = new Exam(1, "04.07.2021", 10);
Exam examThree = new Exam(3, "04.07.2021", 9);
exams.put(null, "Zero");
exams.put(examOne, "One");
exams.put(examTwo, "Two");
exams.put(examThree, "Three");
exams.forEach((k, v) -> {
System.out.println("Key: " + k);
System.out.println("Value: " + v);
});
}
}
class Exam {
long id;
String date;
int mark;
public Exam(long id, String date, int mark) {
this.id = id;
this.date = date;
this.mark = mark;
}
@Override
public String toString() {
return "Exam{" +
"id=" + id +
", date='" + date + '\'' +
", mark=" + mark +
'}';
}
}