Hi,
How would you sort an array list alphabetically or numerically? I am not really sure how a method sorting an array either alphabetically or numerically would work.
Thanks!
Hi,
How would you sort an array list alphabetically or numerically? I am not really sure how a method sorting an array either alphabetically or numerically would work.
Thanks!
[Collections.sort][1] will sort by default ordering. This is lexical (alphabetical) for strings and numerical for numeric data types. You can also specify your own comparator if you need non-standard ordering.
For example:
ArrayList list = new ArrayList();
list.add(1);
list.add(10);
list.add(-1);
list.add(5);
Collections.sort( list );
[1]: http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator)
The Collections.sort methods allow one to sort a list with a Comparator that implements your particular sorting method (e.g. alphabetic or numeric sort).
Collections.sort(list,new Comparator() {
int compare(T o1, T o2) { // implement your own logic here }
boolean equals(Object obj) { // implement your own logic here } }