Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I implement Comparable more than once?

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.

like image 353
user26270 Avatar asked Apr 21 '10 18:04

user26270


People also ask

How many methods does comparable have?

The Comparator class provides two essential methods for sorting: comparing and thenComparing . The comparing method is passed the value to be compared first, and the thenComparing method is the next value to be compared.

What does it mean to implement comparable?

The fact that a class implements Comparable means that you can take two objects from that class and compare them.

Can we implement comparable interface?

We can implement the Comparable interface with the Movie class, and we override the method compareTo() of Comparable interface.


1 Answers

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>
like image 163
mkorpela Avatar answered Oct 23 '22 05:10

mkorpela