Java 接口扩展了 Comparable [英] Java interface extends Comparable

查看:25
本文介绍了Java 接口扩展了 Comparable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个由 T A<T> 参数化的接口 A,并且还希望实现它的每个类也实现Comparable(与 T 及其子类型).编写 interface A<T> 看起来很自然.扩展可比性,但这不起作用.那我该怎么做呢?

I want to have an interface A parameterised by T A<T>, and also want every class that implements it to also implement Comparable (with T and its subtypes). It would seem natural to write interface A<T> extends Comparable<? extends T>, but that doesn't work. How should I do it then?

推荐答案

When Comparable 出现这意味着你有一个 Comparable 的实例,它可以与 T 的一个(未知)子类型进行比较,而不是它可以与任何 T 的子类型.

When Comparable<? extends T> appears it means you have an instance of Comparable that can be compared to one (unknown) subtype of T, not that it can be compared to any subtype of T.

但是你不需要那个,因为 Comparable 无论如何都可以将自己与 T 的任何子类型进行比较,例如Comparable 可以将自身与 Comparable 进行比较.

But you don't need that, because a Comparable<T> can compare itself to any subtype of T anyway, e.g. a Comparable<Number> can compare itself to a Comparable<Double>.

那就试试吧:

interface A<T> extends Comparable<T> {
    // ...
}

interface A<T extends Comparable<T>> extends Comparable<A<T>> {
    // ...
}

取决于您是否需要能够比较 T 的实例以实现您的 compareTo 方法.

depending on whether you need to be able to compare instances of T in order to implement your compareTo method.

这篇关于Java 接口扩展了 Comparable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆