在 Java 中,为接口(interface)的所有实现提供自然排序的最佳方法是什么?
我有一个接口(interface),我想通过扩展Comparable
接口(interface)来确保/提供所有实现之间的自然排序:
public interface MyInterface extends Comparable<MyInterface> {
}
此接口(interface)将有多个实现,每个实现都可以为其自己的实例定义自然排序,但可能不知道如何根据其他实现对自己进行排序。
我使用的一种方法是引入递归泛型并按实现和实例拆分自然顺序比较:
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);
}
这意味着 MyInterface
的实现只需在它们自己的实例之间进行比较:
public class MyClass implements MyInterface<MyClass> {
public int compare(MyClass other) {
return 0; // ... or something more useful...
}
}
但是,递归泛型可能会变得非常难以维护。
有更好的方法吗?
最佳答案
您可以移动此铸件 compare((X) o);
从接口(interface)的默认方法到实现,因此您不需要通用 <X extends MyInterface<X>>
完全没有。
public interface MyInterface extends Comparable<MyInterface> {
@Override
default int compareTo(MyInterface o) {
...
comp = compare(o);
...
}
int compare(MyInterface other);
}
在这种情况下,实现可能如下所示:
public class MyClass implements MyInterface {
private Integer property;
public int compare(MyInterface other) {
return Integer.compare(this.property, ((MyClass) other).property);
}
}
关于java - 如何为接口(interface)的所有实现实现compareTo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55749646/