如何在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步 – 打印所需的结果。
语法
要获得一个数组的长度(数组中的元素数量),数组有一个内置的属性,即长度。
以下是它的语法
array.length
其中,’array’指的是数组引用。
多种方法
我们已经提供了不同方法的解决方案。
通过使用静态数组和length()方法。
通过使用用户定义的方法和length()方法。
通过使用无效检查。
让我们逐一看看这个程序和它的输出。
方法一:通过使用静态数组和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:通过使用无效检查
示例
这里数组被声明为空,意味着没有元素。在一个if条件下,借助等于运算符检查数组是否为空。
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中检查一个数组是否为空。