Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java interface extends Comparable

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?

like image 933
oceola Avatar asked Feb 09 '10 19:02

oceola


People also ask

Can an interface implement comparable?

In general, if you mark an interface as Comparable to itself, any correct implementation may only use methods from this interface to perform the comparison. Otherwise this relation can't be made anti-symmetric - a necessary condition to have a consistent ordering.

Is comparable a Java interface?

Java Comparable interface is used to order the objects of the user-defined class. This interface is found in java. lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only.

What is comparable [] in Java?

The Comparable interface is used to compare an object of the same class with an instance of that class, it provides ordering of data for objects of the user-defined class. The class has to implement the java.

What does T extends Comparable mean in Java?

Java- The meaning of <T extends Comparable<T>> ? a) Comparable <T> is a generic interface (remember it's an "interface" i.e not a "class") b) extends means inheritance from a class or an interface.


2 Answers

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.

like image 154
finnw Avatar answered Sep 23 '22 01:09

finnw


If you use comparable you do not need to specify the possibility for subtypes in the compare function, it is by nature possible to pass in any subtype of an object X into a method that declared a parameter of class X. See the code below for more information.

public interface Test<T> extends Comparable<T> {

}

class TestImpl implements Test<Number> {
    @Override
    public int compareTo(final Number other) {
        return other.intValue() - 128;
    }
}

class TestMain {
    public static void main(final String[] args) {
        TestImpl testImpl = new TestImpl();
        testImpl.compareTo(Integer.MIN_VALUE);
    }
}
like image 23
Nils Schmidt Avatar answered Sep 22 '22 01:09

Nils Schmidt