3

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?

2
  • 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? Commented Nov 7, 2012 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. Commented Nov 7, 2012 at 2:57

1 Answer 1

5

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));
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

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>>
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.
for best results use Comparable<? super T>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.