界面Delayed需要任何
implementation of this interface [to] define a compareTo method that provides an ordering consistent with its getDelay method.
但是我想知道,为什么 Java 8 中没有默认实现,因为契约(Contract)要求 compareTo
仅依赖于 getDelay
。
将此留给实现类是否有特定原因?还是覆盖超接口(interface)时无法创建默认方法?
编辑:为了让我的问题更容易理解,这里有一个例子:
interface Delayed extends Comparable<Delayed> {
long getDelay(TimeUnit unit);
@Override
default int compareTo(Delayed o) {
// might not be the perfect "compareTo" implementation, but you get the point
return o == this? 0:
Long.compare(this.getDelay(TimeUnit.NANOSECONDS), o.getDelay(TimeUnit.NANOSECONDS);
}
}
最佳答案
简单的答案是 Delayed
从 1.5 开始存在,default
方法从 1.8 开始存在。因此,为了提供 compareTo
方法作为 default
方法,必须有意更改接口(interface)。
如果没有发生,可能有以下几种原因:
- 可能根本没有人考虑过
它可能被考虑过但被放弃了,因为:
- 可能存在兼容性问题
- 预期 yield 不足以证明 API 更改的合理性
- 在发布前有优先级更高的事情要做
对我来说,这看起来不像是一个高优先级的问题。大多数时候,您会在 JRE 提供的 ScheduledExecutorService
上下文中遇到 Delayed
实现,这些实现已经存在,因此不会从此类更改中受益。
我不认为您会经常在应用程序代码中遇到自定义 Delayed
实现,但即使您看到它不同,JRE 开发人员显然决定专注于有用性更明显的添加(或不太值得商榷)。
想了想,纳入the discussion关于 getDelay()
契约(Contract)与 Comparable
契约(Contract)的结合,如果 Delayed
从未扩展 Comparable
完全没有。毕竟,使用 Comparator
或类似的设计模式按属性对对象进行排序并不难。
关于java - 为什么 Delayed 不为 compareTo 提供默认方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33918758/