Thursday, May 19, 2011

Sorting an ArrayList in java

If the data in your ArrayList has a natural sorting order (ie, implements Comparable, as do String, Integer, ...), you can simply call the static Collections.sort() method. This is a stable, guaranteed n log n sort.
Collections.sort(yourArrayList);
If you want to choose a different sort criterion or your data doesn't implement xxxx, you will have to define a Comparator and pass that to the sort() method.
Collections.sort(yourArrayList, yourComparator);
Check out Collections for other useful utility methods.

No comments:

Post a Comment

Chitika