Implementing Comparable in an Interface

I call a specific class using only its interface. The problem is that the class itself implements Comparable, but since I mean the class through a different interface, the compiler does not know that it implements Comparable. I am sure this is a simple solution ... but I just can't think about it right now.

+3
source share
5 answers

Will everything that implements the interface be implemented Comparable<T>? If so, I suggest you just extend the interface Comparable<T>.

Otherwise, you can simply click on Comparable<T>if you know that in this case it will work. Of course, this loses some compilation type security, but that is the nature of the beast.

+8
source

This seems strange to me ... if you have a main thing like the following, you can get it to work with the Parent interface and the child classes below ... but there is a weird thing in that you can try comparing ChildA with ChildB, which is probably does not make sense.

Perhaps if you give us a hint of what the classes / interface do, we can give a better answer.

public class Main
{
    public static void main(final String[] argv)
    {
        Parent x;
        Parent y;

        x = new ChildA();
        y = new ChildA();
        x.compareTo(y);
    }
}

abstract interface Parent
    extends Comparable<Parent>
{
}

class ChildA
    implements Parent
{
    public int compareTo(Parent o)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

class ChildB
    implements Parent
{
    public int compareTo(Parent o)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
+1
source

Comapartor. (, ). Comparable . , , .

+1

. , Lickable ( lick()), , Lickable Comparable. :

public <LickableAndComparable extends Lickable & Comparable<LickableAndComparable>> void lickGreater(LickableAndComparable a, LickableAndComparable b) {
    if (a.compareTo(b) > 0) a.lick();
    else b.lick();
}

, Lickable, Comparable. , , , Lickable, Comparable . , . , , .

+1

Comparable interfaces are complex. In general, if you mark an interface as comparable to itself, any correct implementation can only use methods from this interface to perform the comparison. Otherwise, this relation cannot be made antisymmetric - a necessary condition for sequential ordering.

So think twice before marking an interface as comparable.

However, in your case there is a workaround if you are sure that you are not mixing different implementations of the interface:

interface Foo {
}

interface Bar extends Foo, Comparable<Bar> {
}


class FooComparator<T extends Foo & Comparable<T>> implements Comparator<T> {

    @Override
    public int compare(T arg0, T arg1) {
        return arg0.compareTo(arg1);
    }
}
0
source

Source: https://habr.com/ru/post/1770007/


All Articles