TL ; DR:
For objects, == asks if two variables hold the very same object. Override equals to compare the values instead. Override hashCode too, so a HashSet or a HashMap can find equal objects.
@Override
public boolean equals(Object other) {
return other instanceof Time t && hour == t.hour && minute == t.minute;
}
@Override
public int hashCode() {
return Objects.hash(hour, minute);
}
Full lesson:
Two objects can hold the same values and still be two objects. Create new Time(9, 30) twice, as a and b. Then a == b is false.
For objects, == checks identity. It is true only when both variables hold one and the same object.
Equal by value
Every class inherits equals(Object other) from Object. By default it does what == does. Override it to compare the fields.
other instanceof Time t checks that other is a Time. If it is, it names it t. Then compare t's fields with your own.
Sets need a hash code
A HashSet doesn't compare a new item with every item it holds. That would be slow. It files each object under a number, its hash code. Then it calls equals only on objects with the same hash code.
So equal objects must have equal hash codes. hashCode() returns that number. Objects.hash(hour, minute) builds it from the same fields as equals.
Write both
Without hashCode, each object keeps a different default hash code. A HashSet then never compares two equal times. It keeps both.
Strings follow the same rule. Compare two strings with equals, not with ==.
Your task
The Time class keeps an hour and a minute. Override equals and hashCode. Two times are equal when the hour and the minute both match.
mainFunction compares three times. Then it adds them to a HashSet of alarms.
Expected output:
a and b are the same time
a and c are different times
alarms: 2Free plan: 30 tutor messages. Premium is unlimited.
