How to determine if an array is empty in Java?
In Java, we can use the following method to check if an array is empty:
- Determine by checking the length property of an array.
int[] arr = new int[0];
if(arr.length == 0){
System.out.println("数组为空");
} else {
System.out.println("数组不为空");
}
- Determine equality using the equals() method of the Arrays class.
int[] arr = new int[0];
if(Arrays.equals(arr, new int[0])){
System.out.println("数组为空");
} else {
System.out.println("数组不为空");
}
- Determine using the toString() method of the Arrays class:
int[] arr = new int[0];
if(Arrays.toString(arr).equals("[]")){
System.out.println("数组为空");
} else {
System.out.println("数组不为空");
}
The above are several commonly used methods to determine if an array is empty; choose the appropriate method based on the actual situation.