开发者

sorting string arraylist in android [duplicate]

This question already has answers here: Sorting arraylist in alphabetical order (case insensitive) 开发者_开发问答 (10 answers) Closed 7 years ago.

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();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜