Natural Ordering with Comparable
Student already overrides equals and hashCode, considering two students equal when their ids match:
public class Student {
private int id;
private String name;
private double gpa;
// constructor, getters ...
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student other = (Student) o;
return id == other.id;
}
@Override
public int hashCode() {
return Integer.hashCode(id);
}
}
Solution
<, >, and the other comparison operators work only on primitive numbers; Java has no built-in order for objects. To give a type an order, it implements Comparable<T> and provides compareTo(T other). The return value follows a fixed convention: negative if this comes before other, zero if the two are equal in order, positive if this comes after other.
Solution
public class Student implements Comparable<Student> {
// ...fields, constructor, equals, hashCode as above...
@Override
public int compareTo(Student other) {
return Integer.compare(this.id, other.id);
}
}
Consistent means compareTo returns 0 exactly when equals returns true. Ordering by id gives that, since equals also keys on id. Two students with the same id are equal, and they compare as equal in order too. Ordering by gpa would break this. Two different students can share a GPA. They would compare as equal, compareTo returning 0, even though equals says they are different students.