I have an array filled with Integer objects that I'm looking to sort via the built-in ArrayList sort method. I'm not looking to do this via Collection.sort. Do I have to implement a comparator method to then pass to the sort method?
2 Answers
The ArrayList.sort method does take a comparator which can be used to specify the sorting criteria, but as mentioned on the documentation page, passing it a null comparator is also valid:
If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements' natural ordering should be used.
And as you can see from the Integer documentation, Integer implements Comparable<Integer>, so it has a natural ordering.
So to sort your ArrayList<Integer> you can just do:
ArrayList<Integer> arr = new ArrayList<>();
...
arr.sort(null); // Null comparator forces sort by natural ordering
nullinstead of a comparator, and it'll sort integers by their default ordering.