在Java中,一个空数组通常使用 `null` 表示,因为数组是一个对象,而 `null` 值表明该对象不存在。如果你尝试访问一个 `null` 数组,将会抛出 `NullPointerException`。
1. 使用数组的 `length` 属性:
int[] arr = new int;
if (arr.length == 0) {
System.out.println("数组为空");
} else {
System.out.println("数组不为空");
}
2. 使用 `Arrays.equals` 方法:
int[] arr = new int;
if (Arrays.equals(arr, new int)) {
System.out.println("数组为空");
} else {
System.out.println("数组不为空");
}
3. 使用 `Arrays.stream` 方法结合 `count` 方法:
int[] arr = new int;
if (Arrays.stream(arr).count() == 0) {
System.out.println("数组为空");
} else {
System.out.println("数组不为空");
}
4. 使用 `Objects.isNull` 方法(需要Guava库):
import com.google.common.base.Objects;
int[] arr = new int;
if (Objects.isNull(arr)) {
System.out.println("数组为空");
} else {
System.out.println("数组不为空");
}
请注意,只有第一种方法可以同时判断数组是否为 `null` 和长度是否为 `0`,其他方法只能判断数组长度是否为 `0`