java 在android中排序字符串arraylist
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5814791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sorting string arraylist in android
提问by andro-girl
I have a string arraylist called names. How do I sort the arraylist in alphabetical order?
我有一个名为names的字符串数组列表。如何按字母顺序对数组列表进行排序?
回答by Aleadam
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
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).
根据其元素的自然顺序,将指定列表按升序排序。列表中的所有元素都必须实现 Comparable 接口。此外,列表中的所有元素必须相互比较(即,e1.compareTo(e2) 不得为列表中的任何元素 e1 和 e2 抛出 ClassCastException)。
String
implements Comparable
:
String
实施Comparable
:
java.lang Class String
java.lang.Object extended by java.lang.String
All Implemented Interfaces: Serializable, CharSequence, Comparable
java.lang 类字符串
由 java.lang.String 扩展的 java.lang.Object
所有实现的接口:Serializable、CharSequence、Comparable
http://download.oracle.com/javase/6/docs/api/java/lang/String.html
http://download.oracle.com/javase/6/docs/api/java/lang/String.html
回答by Aleadam
Another solution but Collections.sort()
is best. I just want to show alternative
另一种解决方案,但Collections.sort()
最好。我只是想展示替代品
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);
回答by Polyomino
import java.util.Collections;
导入 java.util.Collections;
then use Collections.sort();
然后使用 Collections.sort();