java - 如何为接口的所有实现实现 compareTo?
问题描述
在 Java 中,为接口的所有实现提供自然排序的最佳方法是什么?
我有一个接口,我想通过扩展Comparable
接口来确保/提供所有实现之间的自然排序:
public interface MyInterface extends Comparable<MyInterface> {
}
该接口将有多个实现,每个实现都可以为自己的实例定义自然排序,但可能不知道如何根据其他实现对自己进行排序。
我使用的一种方法是引入递归泛型并通过实现和实例拆分自然顺序比较:
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);
从接口的默认方法移动到实现,因此您根本不需要泛型<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);
}
}
推荐阅读
- pdf - 当列表单元格中有多行时,PDF输出很丑
- reactjs - 无法通过在 REACT 中使用 Google 身份验证使用登录 ID 从 Firestore 读取数据。我的数据以当前使用的 ID 保存在 Firestore 中
- go - 用于大容量服务的 opentracing-go
- reactjs - 导出从 ReactJS 中的异步函数获取的常量?
- php - PHP日语字符验证
- mongodb - mongodb 更改流 - pymongo
- javascript - 在另一个屏幕导航 V5 REACT-NATIVE 中从屏幕获取参数
- android - 如何在 Android Kotlin 中将 MainActivity 代码转换为片段
- python - 使用 plotly/dash 为绘图创建背景图像
- wordpress - 在 wordpress 中显示自定义用户配置文件字段