我怎样才能多次实现Comparable?
我正在将一些代码升级到 Java 5,但我显然不理解泛型的某些内容。我还有其他类实现了一次 Comparable,我已经能够实现了。但现在我有了一个类,由于继承,它最终尝试实现两种类型的 Comparable 。这是我的情况:
我有以下类/接口:
interface Foo extends Comparable<Foo>
interface Bar extends Comparable<Bar>
abstract class BarDescription implements Bar
class FooBar extends BarDescription implements Foo
这样,我收到错误“接口 Comparable 无法使用不同的参数多次实现...”
为什么我不能实现compareTo(Foo foo)在 FooBar 中,以及在 BarDescription 中实现的compareTo(Bar) ?这不就是简单的方法重载吗?
编辑:我有许多扩展 BarDescription 的类。如果我删除 Bar 上 Comparable 的类型参数,使其保持原始状态,那么在对扩展 BarDescription 的所有类进行排序时,我会收到一堆编译器警告。用下面的通配符答案可以解决这个问题吗?这个答案看起来相当复杂并且难以理解维护。
I'm upgrading some code to Java 5 and am clearly not understanding something with Generics. I have other classes which implement Comparable once, which I've been able to implement. But now I've got a class which, due to inheritance, ends up trying to implement Comparable for 2 types. Here's my situation:
I've got the following classes/interfaces:
interface Foo extends Comparable<Foo>
interface Bar extends Comparable<Bar>
abstract class BarDescription implements Bar
class FooBar extends BarDescription implements Foo
With this, I get the error 'interface Comparable cannot be implemented more than once with different arguments...'
Why can't I have a compareTo(Foo foo) implemented in FooBar, and also a compareTo(Bar) implemented in BarDescription? Isn't this simply method overloading?
Edit: I have many classes which extend BarDescription. If I remove the type parameter for Comparable on Bar, leaving it in the raw state, then I get a bunch of compiler warnings when sorting all the classes which extend BarDescription. Would this be solved with the wildcards answer below? That answer looks quite complicated and difficult to understand for maintenance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译字节码后,泛型不存在。
限制:您不能实现/扩展两个或多个在没有泛型参数的情况下相同且与泛型参数不同的接口/类。
如果你真的想要类型安全,你可以做的是:
Generics don't exist after bytecode has been compiled.
Restrictions from this: You can't implement / extend two or more interfaces / classes that would be same without the generic parameter and are different with the generic parameter.
What you could do if you really really want type safety is:
我会编写几个
Comparator
并完成它。I'd write a couple of
Comparator
s and be done with it.当您考虑通配符时,拥有通用接口的多个实现会遇到问题。
这不依赖于擦除。
Having multiple implementations of generic interfaces would run into problems when you consider wildcards.
This does not depend upon erasure.