首页 > 解决方案 > 如何为接口的所有实现实现 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... 
  }
}

但是,递归泛型可能变得非常难以维护。

有没有更好的办法?

标签: javagenericsinterfacecompareto

解决方案


您可以将此转换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);
    }
}

推荐阅读