本文介绍了我怎样才能不止一次地实现Comparable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些代码升级到Java 5,显然不了解泛型的一些内容。我有其他类实现了Comparable一次,我已经能够实现。但是现在我已经有了一个类,它由于继承而最终试图实现两种类型的Comparable。这是我的情况:

我有以下类/接口:

  interface Foo extends Comparable< Foo> 

界面栏扩展了Comparable< Bar>

抽象类BarDescription实现Bar

class FooBar extends BarDescription implements Foo

有了这个,我得到错误'接口Comparable不能多次使用不同的参数来实现...'。

为什么我不能拥有在FooBar中实现的compareTo(Foo foo),以及在BarDescription中实现的compareTo(Bar)?这不是简单的方法重载吗?



编辑:我有很多扩展BarDescription的类。如果我删除Comparable on Bar的类型参数,将其保留在原始状态,那么当对所有扩展BarDescription的类进行排序时,我会得到一堆编译器警告。这是通过下面的通配符来解决的吗?这个答案看起来相当复杂,难以理解维护。 解决方案

字节码编译完成后,泛型不存在。



由此产生的限制:您无法实现/扩展两个或更多接口/类,它们在没有通用参数的情况下是相同的,并且与通用参数不同。



如果您真的想要类型安全,您可以做什么:

  interface Foo< ; T延伸Foo≠0。扩展了Comparable< T> 
interface Bar< T extends Bar<>>扩展了Comparable< T>
抽象类BarDescription< T extends Bar<>>实现Bar< T>
class FooBar扩展BarDescription< FooBar>实现Foo< FooBar>


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.

解决方案

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:

interface Foo<T extends Foo<?>> extends Comparable<T>
interface Bar<T extends Bar<?>> extends Comparable<T>
abstract class BarDescription<T extends Bar<?>> implements Bar<T>
class FooBar extends BarDescription<FooBar> implements Foo<FooBar>

这篇关于我怎样才能不止一次地实现Comparable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 11:31