Sobes.tech
Junior — Senior

Proper use of key objects in HashMap

livecode

Task condition

The example uses HashMap<Exam, String>, where instances of the Exam class serve as keys. It is necessary to implement a correct comparison mechanism for Exam objects so that the HashMap correctly handles duplicate keys.

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 +
                '}';
    }
}

// To ensure correct handling of duplicate keys, override equals() and hashCode() in Exam class.
// Example:
// @Override
// public boolean equals(Object o) {
//     if (this == o) return true;
//     if (o == null || getClass() != o.getClass()) return false;
//     Exam exam = (Exam) o;
//     return id == exam.id && mark == exam.mark && Objects.equals(date, exam.date);
// }
//
// @Override
// public int hashCode() {
//     return Objects.hash(id, date, mark);
// }