The compiler thinks a comparable type is not comparable

So, I have a class that implements Comparable (for brevity, a dummy method is used here)

public class MarkovEntry<T extends Chainable> implements Comparable<MarkovEntry<T>>
{
    // Compare two rows by ID
    public int compareTo(MarkovEntry<T> e)
    {
        return 0;
    }
}

And a method in another class that accepts a comparable (again, dummy method)

public class ArrayOps
{
    public static int binSearch(ArrayList<Comparable> list, Comparable c)
    {
        return 0;
    }
}

However, when I try to call my method as follows

int index = ArrayOps.binSearch(entries, newEntry);

Where the ArrayList entries from MarkovEntry and newEntry are MarkovEntry, the compiler tells me

actual argument java.util.ArrayList<com.company.MarkovEntry<T>> cannot be converted 
to java.util.ArrayList<java.lang.Comparable> by method invocation.

What's going on here? MarkovEntry specifically implements Comparable - why doesn't the compiler recognize it?

My class Chain tools are also comparable, in case this has anything to do with it.

+4
source share
1 answer

Generics are a little strange in that

ArrayList<SuperType>

ArrayList<SubType>

. ArrayList<Number> ArrayList<Integer>. , , ArrayList<Number> ArrayList<Integer>, , , .

, , :

ArrayList<Number> list = new ArrayList<Integer>();

Double list, list ArrayList<Number>! , , generics, .


, , , :

public static <T extends Comparable<? super T>> int binSearch(ArrayList<T> list)

, , .

: http://docs.oracle.com/javase/tutorial/extra/generics/methods.html

+5

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


All Articles