How to sort a list of Strings or Integers in Java

要排序ArrayList你可以用
Collections.sort() 這個static方法

例:
import java.util.*;
public class Jtest {
public static void main(String[] args) {
//初始化ArrayList
ArrayList<String> myList = new ArrayList<String>();
myList.add(“Balance”);
myList.add(“Apple”);
myList.add(“Design”);
myList.add(“Center”);

//將排序前的資料顯示出來
System.out.println(“排序前:”);
for (String str : myList) {
System.out.println(str);
}

//進行排序
Collections.sort(myList);
System.out.println(“\n”);

//將排序後的資料顯示出來
System.out.println(“排序後:”);
for (String str : myList) {
System.out.println(str);
}
}
}

執行結果:

排序前:
Balance
Apple
Design
Center

排序後:
Apple
Balance
Center
Design


Following on from our introduction to sorting in Java, we consider here one of the simplest cases of sorting a List of simple objects such as Strings or Integers. Let’s say we have a simple list of Strings:

List<String> words = new ArrayList<String>(50);
words.add("once");
words.add("upon");
words.add("a");
words.add("time");
...

Now, we can sort this list with a simple call to the following library method:

Collections.sort(words);

The Collections.sort() method will work “out of the can” on lists of various “basic” objects that you’d expect to be able to sort, including instances of Number– the primitive wrapper classes IntegerLongFloat etc plus BigInteger and BigDecimal.

Sorting an array

Sorting an array of these objects is just as easy1:

Arrays.sort(myArray);

The above method takes an array of objects, but the Arrays class also provides similar methods for sorting primitive arrays.

相關文章

寫留言

你的電子郵件位址並不會被公開。 必要欄位標記為 *