Solution: Value Equality
Two cards should count as the same card when they have the same rank and the same suit. Right now Card inherits equals from Object, and that version only checks whether two references point to the same object. So a freshly built seven of diamonds is not equal to another seven of diamonds. Let’s fix that.
Solution
The parameter has to be Object, because we are overriding the method Card inherited from Object. A narrower Card parameter would give us a different method, not an override.
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Card other = (Card) o;
return rank == other.rank && suit == other.suit;
}
@Override
public int hashCode() {
return Objects.hash(rank, suit);
}
The body does the same steps as Student.equals. First we check whether the two references point to the same object. Then we reject null and any object of a different class. Now we know the class, so we can cast. Then we compare the fields.
hashCode uses Objects.hash, which builds one hash code out of several values. Student only needs Integer.hashCode(id) because a single field decides equality there. Here both fields decide equality, so both fields have to go into the hash. Otherwise two cards that equals calls equal could have different hash codes.