سؤال

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

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 takes a Comparable (once again, dummy method)

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

Yet when I try to call my method as follows

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

Where entries is an ArrayList of MarkovEntry's and newEntry is a 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 is going on here? MarkovEntry specifically implements Comparable -- why doesn't the compiler recognize that?

My class Chainable implements Comparable as well, in case that has anything to do with it.

هل كانت مفيدة؟

المحلول

Generics are a little strange in that

ArrayList<SuperType>

is not actually a supertype of

ArrayList<SubType>

e.g. ArrayList<Number> is not a supertype of ArrayList<Integer>. This is because if such a relationship held you could substitute in an ArrayList<Number> for an ArrayList<Integer>, which would then allow operations that would have been illegal if you didn't make the replacement.

To be more specific, say you did this:

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

You'd then be able to put in a Double into list because to the compiler, list is an ArrayList<Number>! As you can see, this breaks the guarantees that generics should provide, so it isn't allowed.


What you're looking for is a generic method like this:

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

Basically, you can generify methods the same way you can generify classes.

More info can be found here: http://docs.oracle.com/javase/tutorial/extra/generics/methods.html

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top