sorting string arraylist in android [duplicate]
I have a string arraylist called names. How do I sort the arraylist in alphabetical order?
ArrayList<String> names = new ArrayList<String>();
names =fillNames() // whatever method you need to fill here;
Collections.sort(names);
http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29
Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
String
implements Comparable
:
java.lang Class String
java.lang.Object extended by java.lang.String
All Implemented Interfaces: Serializable, CharSequence, Comparable
http://download.oracle.com/javase/6/docs/api/java/lang/String.html
Another solution but Collections.sort()
is best. I just want to show alternative
ArrayList<String> strings = new ArrayList<String>();
strings.add("a");
strings.add("ab");
strings.add("aa");
String[] stringsArray = new String[strings.size()];
strings.toArray(stringsArray);
Arrays.sort(stringsArray);
List<String> sorted = Arrays.asList(stringsArray);
System.out.println(sorted);
import java.util.Collections;
then use Collections.sort();
精彩评论