Java 中已實現 Comparable 介面的陣列和包裝類的元素排序
Java 提供各種排序演算法和方法,可以幫助我們對陣列、列表或任何集合進行排序。Comparable 介面是一種額外的方法,當我們想要按自然順序對自定義物件進行排序時非常有用。例如,它按字典順序對字串排序,按數字順序對數字排序。此介面位於 ‘java.lang’ 包中。
在本文中,我們將建立一個數組和一個數組列表,然後嘗試對它們進行排序,以顯示陣列和包裝類已經實現了 Comparable 介面。
陣列和包裝類的元素排序
我們將使用以下方法對集合和陣列的元素進行排序:
Collections.sort() 方法
Collection 介面的 ‘Collections’ 類提供了一個名為 ‘Collections.sort()’ 的靜態方法,可以對指定集合(如 ArrayList 或 LinkedList)的元素進行排序。它位於 ‘java.util’ 包中。
語法
Collections.sort( nameOfcollection );
Arrays.sort() 方法
它是 Arrays 類的靜態方法,它接受一個引數並相應地對其元素進行排序。此方法可以對數字資料型別(如整數或雙精度數)的陣列以及字元陣列和字串陣列進行排序。
語法
Arrays.sort( nameOfarray);
演算法
步驟 1 - 我們將從匯入 ‘java.util’ 包開始,以便我們可以使用上面討論的方法。
步驟 2 - 現在建立一個名為 ‘araySort’ 的方法。在此方法中,宣告並初始化一個名為 ‘aray’ 的整數型別陣列。接下來,我們將使用內建方法 ‘Arrays.sort()’ 將給定陣列的元素按升序排序。然後,使用 for each 迴圈列印新排序的陣列。
步驟 3 - 建立另一個名為 ‘araylistSort()’ 的使用者定義方法。在此方法中,我們定義一個包裝類 Integer 的陣列列表,並使用 ‘add()’ 方法向其中新增元素。現在使用內建方法 ‘Collections.sort()’ 將給定陣列列表的元素按升序排序。然後,在 for 迴圈中使用 ‘get()’ 方法按排序順序列印陣列列表的元素。
步驟 4 - 最後,在 main() 方法中,我們將呼叫這兩個方法來執行它們各自的操作。
示例
import java.util.*;
public class Comp1 {
public static void araySort() {
int aray[] = {9, 3, 56, 0, -2, -6, 2, 1, 80};
System.out.print("The given unsorted array: ");
// to print original unsorted array
for (int print : aray) {
System.out.print(print + " ");
}
Arrays.sort(aray);
// to sort the given array
System.out.println();
System.out.print("The newly sorted array: ");
// to print newly sorted array
for (int print : aray) {
System.out.print(print + " ");
}
System.out.println();
}
public static void araylistSort() {
// Creating arraylist of Wrapper class Integer
ArrayList<Integer> araylist = new ArrayList<Integer>();
// Adding elements in arraylist
araylist.add(8);
araylist.add(5);
araylist.add(2);
araylist.add(9);
araylist.add(4);
araylist.add(7);
System.out.println("Elements of the list : ");
// loop to iterate through elements
for(int i = 0; i < araylist.size(); i++ ) {
// to print the elements in the list
System.out.print(araylist.get(i) + " ");
}
Collections.sort(araylist);
// to sort the collection
System.out.println();
System.out.println("Elements of the newly sorted list : ");
for(int i = 0; i < araylist.size(); i++ ) {
// to print the elements of newly sorted list
System.out.print(araylist.get(i) + " ");
}
}
public static void main(String args[]) {
// method call
araySort();
araylistSort();
}
}
輸出
The given unsorted array: 9 3 56 0 -2 -6 2 1 80 The newly sorted array: -6 -2 0 1 2 3 9 56 80 Elements of the list : 8 5 2 9 4 7 Elements of the newly sorted list : 2 4 5 7 8 9
我們建立的方法是靜態的,因此我們不需要建立任何物件來呼叫它們。
結論
您可能已經注意到,我們沒有顯式實現 Comparable 介面,但我們能夠使用 ‘sort()’ 對陣列和包裝類的元素進行排序。原因是它們隱式地實現了 Comparable 介面。
在本文中,我們瞭解了這兩個內建方法 ‘Arrays.sort()’ 和 ‘Collections.sort()’ 在排序方面如何有用。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP