0

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.

1
  • 1
    Shouldn't p1.length be p1.size()? So you have an array of ArrayLists and you're trying to use Collections.sort to sort the array...? Commented Mar 16, 2017 at 21:53

1 Answer 1

2

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

1 Comment

I'd be seriously careful before you answer this, and have a REALLY close look at how they are creating adjacency ;)

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.