sorting string arraylist in android [duplicate]

霸气de小男生 提交于 2019-12-30 11:23:35

问题


I have a string arraylist called names. How do I sort the arraylist in alphabetical order?


回答1:


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




回答2:


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



回答3:


import java.util.Collections;

then use Collections.sort();



来源:https://stackoverflow.com/questions/5814791/sorting-string-arraylist-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!