I have a list of points. I represented this as an ArrayList of ArrayLists. I'm trying to use generics so that the list can store Integers, Floats, etc. and treat them the same. So I have:

ArrayList<ArrayList<? extends Number>>. 

I need to compare these lists based on one element in each inner list.

So to do that I wrote a custom Comparator that I'm using in Collections.sort

The Comparator looks like:

int compare(ArrayList<? extends Number> a, ArrayList<? extends Number> b )
{
    return a.get(index).compareTo(b.get(index))
}

This doesn't compile of course. The compiler complains that there is no compareTo method for the wildcard class.

Is what I'm trying to do even possible?

share|improve this question
How are you going to handle points with different dimensions with this structure? E.g. What if you have (1,1,1) and (2,1) and have chosen the third element to compare on? – Iskar Jarak Nov 7 '12 at 2:54
That's actually another problem in itself. Right now I just check that all the points are of the proper dimension and throw an error otherwise. – Bryan Glazer Nov 7 '12 at 2:57
feedback

1 Answer

up vote 5 down vote accepted

How about defining your Comparator class as:

class MyComparator<T extends Number & Comparable<T>> 
                                          implements Comparator<ArrayList<T>> {
    @Override
    public int compare(ArrayList<T> a, ArrayList<T> b) {
        return a.get(index).compareTo(b.get(index));
    }
}
share|improve this answer
Thank you that works perfectly. I'm new to generics, could you tell me what the concept at work here is? Especially this: MyComparator<T extends Number & Comparable<T>> – Bryan Glazer Nov 7 '12 at 2:58
Well T extends Number & Comparable<T>> implies that T is a Number and that it is Comparable - which is essentially what you want. This is a good resource to learn about generics. This is good for bounded type parameters. – A. R. S. Nov 7 '12 at 3:02
for best results use Comparable<? super T> – newacct Nov 7 '12 at 3:52
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.