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

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

问题描述

我想要一个由 T A< T>参数化的接口 A / code>,并且还希望每个实现它的类也实现 Comparable (带有 T 及其亚型)。编写界面A< T>似乎很自然。扩展Comparable< ;?扩展T> ,但这不起作用。那么我应该怎么做呢?

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



但你不需要这样做,因为无论如何, Comparable< T> 可以将它本身与任何 T 子类型进行比较,例如 Comparable< Number> 可以将它自身与比较< Double>



所以试试:

  interface A< T>扩展了Comparable< T> {
// ...
}

  interface A< T扩展Comparable< T>>扩展Comparable< A< T>> {b $ b // ... 
}

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


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<? 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.

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>.

So try:

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

or

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

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天全站免登陆