Reputation: 385
I have an adjacency list implemented using a List[] of ArrayLists. I want to sort the List in descending order of the size of the ArrayLists. I figured I would do this by writing a Comparator... But how would I do this? or is this just not possible and I should do it another way?
Collections.sort(adjacency, new Comparator<ArrayList<Integer>()>() {
public int compare(ArrayList<Integer> p1, ArrayList<Integer> p2) {
return Integer.compare(p1.length, p2.length);
}
});
The code on top is not functioning. I tried with just an ArrayList, List[], List as a Comparator type. Is there a wrapper class for list? Sorry if this may sound uneducated.
This is how I made the adjacency list:
List<Integer>[] adjacency;
adjacency = (List<Integer>[]) new List[size];
for (int i = 0; i < size; ++i) {
adjacency[i] = new ArrayList<Integer>();
}
Thank you.
Upvotes: 0
Views: 81
Reputation: 48278
The code on top is not functioning.
The code is not working because p1 and p2 are ArrayLists and they dont have a field named length, they have the method size()
, that is what you need.
return Integer.compare(p1.size(), p2.size());
Upvotes: 2