java判断数组是否为空 collection
时间: 2025-01-07 15:03:27 浏览: 86
### Java 中判断数组或集合是否为空
#### 判断数组是否为空
对于数组而言,由于其长度在创建时即已固定不可变,在检查数组是否为空时主要是查看该数组实例是否存在(即不是 `null`),以及它的长度是否为零。
```java
public class ArrayCheck {
public static boolean isArrayEmpty(Object[] array) {
return array == null || array.length == 0;
}
}
```
此方法适用于任何类型的对象数组。如果传入的是基本数据类型数组,则需相应地更改参数类型[^1]。
#### 判断集合是否为空
针对像 `List`, `Set`, 或者更广泛的实现了 `Collection` 接口的数据结构来说,可以利用这些接口提供的内置方法来检测它们是否为空:
- 使用 `isEmpty()` 方法可以直接返回布尔值表示集合内是否有元素存在;
- 可选地也可以通过获取集合大小(`size()`)并验证是否等于零来进行同样的判定操作。
以下是具体例子中的应用方式:
```java
import java.util.*;
public class CollectionCheck {
private static void checkIfCollectionIsEmpty(Collection<?> collection){
System.out.println("Is the given collection empty? " + collection.isEmpty());
// Alternatively, using size()
//System.out.println("Is the given collection empty based on its size? " + (collection.size() == 0));
}
public static void main(String[] args) {
List<Integer> integerList = Arrays.asList();
Set<String> stringSet = new HashSet<>();
checkIfCollectionIsEmpty(integerList);
checkIfCollectionIsEmpty(stringSet);
// Adding elements to demonstrate non-empty case
integerList = Arrays.asList(1, 2, 3);
stringSet.add("example");
checkIfCollectionIsEmpty(integerList);
checkIfCollectionIsEmpty(stringSet);
}
}
```
上述代码展示了如何使用 `isEmpty()` 函数快速有效地测试给定的集合是否含有任何元素[^3]。
阅读全文
相关推荐


















