如何在Java中檢查陣列是否為空
在Java中,陣列是一個物件。它是一種非基本資料型別,用於儲存相同資料型別的多個值。
根據問題陳述,我們需要檢查陣列是否為空。如果陣列中沒有元素或元素數量為零,則稱該陣列為空陣列。
讓我們探索本文,瞭解如何使用Java程式語言來實現這一目標。
例項
為您展示一些例項
例項1
Suppose the original array is {1,3}.
檢查陣列是否為空後的結果將是:
Array is not empty.
例項2
Suppose the original array is {}.
檢查陣列是否為空後的結果將是:
Array is empty
例項3
Suppose the original array is {1,3,4,7,8}.
檢查陣列是否為空後的結果將是:
Array is not empty
演算法
-
步驟1 - 宣告並初始化一個整數陣列。
-
步驟2 - 獲取陣列的長度。
-
步驟3 - 如果長度等於0,則陣列為空,否則不為空。
-
步驟4 - 列印所需的結果。
語法
要獲取陣列的長度(陣列中元素的數量),陣列有一個內建屬性,即length。
下面是其語法:
array.length
其中,“array”指的是陣列引用。
多種方法
我們提供了多種方法來解決這個問題
-
使用靜態陣列和length()方法。
-
使用使用者自定義方法和length()方法。
-
使用空檢查。
讓我們逐一檢視程式及其輸出。
方法1:使用靜態陣列和length()方法
示例
在這種方法中,陣列元素將在程式中初始化。然後,根據演算法檢查陣列是否為空。
public class Main { //main method public static void main(String[] args) { //Declare and initialize the array elements int arr[] = {1,3,4,7,8}; //check if array is empty or not if(arr.length == 0) { //if length is zero then array is empty. System.out.println("Array is empty."); } else { //otherwise array is not empty. System.out.println("Array is not empty."); } } }
輸出
Array is not empty.
方法2:使用使用者自定義方法和length()方法
示例
在這種方法中,陣列元素將在程式中初始化。然後,透過將陣列作為引數傳遞給使用者自定義方法,並在方法內部根據演算法檢查陣列是否為空。
public class Main{ //main method public static void main(String[] args) { //Declare and initialize the array elements int arr[] = {}; //callin user defined method func(arr); } //user defined method public static void func(int arr[]){ //check if array is empty or not if(arr.length == 0) { //if length is zero then array is empty. System.out.println("Array is empty."); } else { //otherwise the array is not empty. System.out.println("Array is not empty."); } } }
輸出
Array is empty.
方法3:使用空檢查
示例
這裡陣列宣告為null,表示沒有元素。使用if條件和等於運算子檢查陣列是否為null。
public class Main{ public static void main(String[] args){ int arr[] = null; //check if array is equal to null or not by using equal to operator if(arr == null) { System.out.println("Empty array"); } else { System.out.println("Not an empty array"); } } }
輸出
Empty array
在本文中,我們探討了如何在Java中檢查陣列是否為空。
廣告