Search code examples
javaarraysgenericscompareto

Comparing an Array of Comparables in Java


I want to compare an array of comparables. The simplest way seems the following (details not shown):

public class ArrayComparable implements Comparable<ArrayComparable>{
ArrayList<Comparable<?>> list = new ArrayList<Comparable<?>>();

@Override
public int compareTo(ArrayComparable ac) {
    Iterator<Comparable<?>> itr = ac.list.iterator();
    for(Comparable<?> l : list) {
        Comparable<?> itrNext = itr.next();
        if(itrNext.getClass() == l.getClass()) {
            if(itrNext.compareTo(l)) {
                //something
            } else {
                //other stuff
            }
        } else {
            //some other thing
        }
    }
}

Of course the problem here is that the compareTo as in itrNext.compareTo(l) will not work giving the error: The method compareTo(capture#6-of ?) in the type Comparable<capture#6-of ?> is not applicable for the arguments (Comparable<capture#7-of ?>) which I understand why (as far as the method is concerned I might be comparing apples to oranges). On the other hand, I know I am not as I check for the class of things before comparing them.

So is there a way I can make this work? Don't worry about the sanity of comparing arrays of any comparables, as I have a good reason why I want to do that.

EDIT- SO why would I want to do something like this. Say I wanted to have an array of comparables, and I didn't care what was contained in each index, as long as the types corresponded, and they could be compared. Then I could do a general lexicographical compare between these arrays. This way I don't have to write a comparable for (int,int) and (int, string), and (string, double, string) or whatever you need. I just write one, and as long as I make sure that the types match (and I can), I am good to go.


Solution

  • Using the raw type Comparable wherever you're currently using Comparable<?> should work. Actually, you could just do that in one place if you want:

    if (((Comparable) itrNext).compareTo(l) == 0)