In Java, what is the best approach to provide natural ordering for all implementations of an interface?
I have an interface, for which I want to ensure/provide natural ordering between all implementations by extending the Comparable
interface:
public interface MyInterface extends Comparable<MyInterface> {
}
There will be several implementations of this interface, each of which can define a natural ordering for its own instances, but which may not know how to order itself against other implementations.
One approach, which I have used, is to introduce recursive generics and split the natural order comparison by implementation and by instance:
public interface MyInterface<X extends MyInterface<X>> extends Comparable<MyInterface> {
@Override
default int compareTo(MyInterface o) {
// the interface defines how to compare between implementations, say...
int comp = this.getClass().getSimpleName().compareTo(o.getClass().getSimpleName());
if (comp == 0) {
// but delegates to compare between instances of the same implementation
comp = compare((X) o);
}
return comp;
}
int compare(X other);
}
This means that the implementations of MyInterface
only have to compare between their own instances:
public class MyClass implements MyInterface<MyClass> {
public int compare(MyClass other) {
return 0; // ... or something more useful...
}
}
But, recursive generics can become very difficult to maintain.
Is there a better way?