Sorting a generic ArrayList of ArrayLists
arraylist, generics, java
Solution
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));
}
}
Problem
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?