判断集合是否为空可以通过以下几种方法:
1. 使用 `isEmpty()` 方法:
```java
List list = new ArrayList<>();
if (list.isEmpty()) {
System.out.println("集合为空");
}
```
2. 使用 `size()` 方法:
```java
Set set = new HashSet<>();
if (set.size() == 0) {
System.out.println("集合为空");
}
```
3. 直接判断集合是否为 `null` 或者是否包含元素:
```java
Map map = new HashMap<>();
if (map == null || map.isEmpty()) {
System.out.println("集合为空");
}
```
4. 使用 `CollectionUtils` 工具类(例如来自 Apache Commons Collections):
```java
import org.apache.commons.collections.CollectionUtils;
List list = new ArrayList<>();
if (CollectionUtils.isEmpty(list)) {
System.out.println("集合为空");
}
```
5. 使用 `StringUtils` 工具类(例如来自 Apache Commons Lang):
```java
import org.apache.commons.lang3.StringUtils;
String str = "";
if (StringUtils.isEmpty(str)) {
System.out.println("字符串为空");
}
```
选择合适的方法取决于具体的场景和需求。需要注意的是,在使用 `isEmpty()` 方法时,如果集合本身为 `null`,会抛出空指针异常,因此应该先判断集合是否为 `null`