排序陣列

使用 Arrays api 可以輕鬆完成對陣列的排序。

import java.util.Arrays;

// creating an array with integers
int[] array = {7, 4, 2, 1, 19};
// this is the sorting part just one function ready to be used
Arrays.sort(array);
// prints [1, 2, 4, 7, 19]
System.out.println(Arrays.toString(array));

排序字串陣列:

String 不是數字資料,它定義了它自己的順序,稱為詞典順序,也稱為字母順序。使用 sort() 方法對 String 陣列進行排序時,它會將陣列排序為 Comparable 介面定義的自然順序,如下所示:

增加訂單

String[] names = {"John", "Steve", "Shane", "Adam", "Ben"};
System.out.println("String array before sorting : " + Arrays.toString(names));
Arrays.sort(names); 
System.out.println("String array after sorting in ascending order : " + Arrays.toString(names));

輸出:

String array before sorting : [John, Steve, Shane, Adam, Ben]    
String array after sorting in ascending order : [Adam, Ben, John, Shane, Steve]

減少訂單

Arrays.sort(names, 0, names.length, Collections.reverseOrder());
System.out.println("String array after sorting in descending order : " + Arrays.toString(names));

輸出:

String array after sorting in descending order : [Steve, Shane, John, Ben, Adam]

對 Object 陣列進行排序

為了對物件陣列進行排序,所有元素都必須實現 ComparableComparator 介面來定義排序順序。

我們可以使用 sort(Object[]) 方法按自然順序對物件陣列進行排序,但是必須確保陣列中的所有元素都必須實現 Comparable

此外,它們也必須是相互可比的,例如 e1.compareTo(e2) 不能為陣列中的任何元素 e1 和 e2 丟擲 ClassCastException 。或者,你可以使用 sort(T[], Comparator) 方法對自定義順序的 Object 陣列進行排序,如以下示例所示。

// How to Sort Object Array in Java using Comparator and Comparable
Course[] courses = new Course[4];
courses[0] = new Course(101, "Java", 200);
courses[1] = new Course(201, "Ruby", 300);
courses[2] = new Course(301, "Python", 400);
courses[3] = new Course(401, "Scala", 500);
       
System.out.println("Object array before sorting : " + Arrays.toString(courses));
       
Arrays.sort(courses);
System.out.println("Object array after sorting in natural order : " + Arrays.toString(courses));
       
Arrays.sort(courses, new Course.PriceComparator());
System.out.println("Object array after sorting by price : " + Arrays.toString(courses));
       
Arrays.sort(courses, new Course.NameComparator());
System.out.println("Object array after sorting by name : " + Arrays.toString(courses));

輸出:

Object array before sorting : [#101 Java@200 , #201 Ruby@300 , #301 Python@400 , #401 Scala@500 ]    
Object array after sorting in natural order : [#101 Java@200 , #201 Ruby@300 , #301 Python@400 , #401 Scala@500 ]    
Object array after sorting by price : [#101 Java@200 , #201 Ruby@300 , #301 Python@400 , #401 Scala@500 ]    
Object array after sorting by name : [#101 Java@200 , #301 Python@400 , #201 Ruby@300 , #401 Scala@500 ]