In java what can be a good hashCode method for a class with a date, where objects are considered equal if the dates have a predefined maximum difference. Example class:
public class Test {
private static final int MILLISECONDS_IN_A_DAY = 24 * 60 * 60 * 1000;
private Date date;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Test other = (Test) o;
return ((date == null && other.date == null) ||
(date != null && other.date != null &&
Math.abs(date.getTime() - other.date.getTime()) < MILLISECONDS_IN_A_DAY));
}
}
Should I explore a different strategy? Perhaps another comparison function, either an internal or an external one? Maybe implementing the Comparable interface would be better?
I would advise against creating a custom
equals()andhashCode()implementation.You would either need to define a comparator for your class:
Or better yet, create a custom comparator: