Created: 2023-09-06 11:59
Status: #concept
Subject: Programming
Tags: Java java.util Java Interface java.util.Comparator java.util.ArrayList java.util.Stream Java Lambda Expression
java.util.Comparable
The
Comparable<T>
imposes an ordering is referred to as the class's natural ordering, and the class's .compareTo(T obj)
method is referred to as its natural comparison method.
- the
.compareTo(T obj)
method must return-1 | 0 | 1
based on whetherx.compareTo(y)
is lesser, equal, or greater thany
. - Lists (and arrays) of objects that implement this interface can be sorted automatically by
Collections.sort
(andArrays.sort
).
Example
public class Member implements Comparable<Member> {
private String name;
private int height;
public Member(String name, int height) {
this.name = name;
this.height = height;
}
public String getName() {
return this.name;
}
public int getHeight() {
return this.height;
}
@Override
public String toString() {
return this.getName() + " (" + this.getHeight() + ")";
}
@Override
public int compareTo(Member member) {
if (this.height == member.getHeight()) {
return 0;
} else if (this.height > member.getHeight()) {
return 1;
} else {
return -1;
}
}
}
Alternatively, it can be implemented like this:
@Override
public int compareTo(Member member) {
return this.height - member.getHeight();
}
We don't necessarily need to return
-1 | 0 | 1
, but rather a negative (less than) or positive (greater than) number.