I have objects that implement an interface so certain methods are available (getTime, getValue, etc).
However I also want to force these objects to be sortable in the same way using Comparable but I can't define bodies in the interface (at least in Android Java).
What can I do?
You can define bodies in an interface using the default
keyword (which is not part of the signature):
public interface MyInterface extends Comparable<MyInterface> {
@Override
default int compareTo(MyInterface other) {
return 0;
}
}
However, if you want to sort on different criteria from time to time. Passing a comparator with the sort
method is a much better choice.
public interface MyInterface {
int getTime();
int getValue();
}
Then call like:
List<MyInterface> list= ...;
list.sort((mi1, mi2) -> Integer.compare(mi1.getTime(), mi2.getTime())); // sorts by time
list.sort((mi1, mi2) -> Integer.compare(mi1.getValue(), mi2.getValue())); // sorts by value