java判断list是否为空,用那个工具类?
时间: 2023-12-16 17:06:33 浏览: 48
在Java中,可以使用Java Collection Framework中的List接口提供的方法来判断一个List是否为空。List接口提供了一个isEmpty()方法,用于判断List是否为空。示例如下:
```java
List<String> myList = new ArrayList<>();
if (myList.isEmpty()) {
System.out.println("List is empty");
} else {
System.out.println("List is not empty");
}
```
另外,Java中也有一些工具类可以用来判断一个集合是否为空,比如Apache Commons Collections中的CollectionUtils类和Guava中的com.google.common.collect.Collections2类。这些工具类提供了一些常用的集合操作方法,包括判断集合是否为空。示例如下:
使用Apache Commons Collections:
```java
import org.apache.commons.collections4.CollectionUtils;
List<String> myList = new ArrayList<>();
if (CollectionUtils.isEmpty(myList)) {
System.out.println("List is empty");
} else {
System.out.println("List is not empty");
}
```
使用Guava:
```java
import com.google.common.collect.Collections2;
List<String> myList = new ArrayList<>();
if (Collections2.isEmpty(myList)) {
System.out.println("List is empty");
} else {
System.out.println("List is not empty");
}
```
这些工具类的使用方式与Java Collection Framework中的List接口类似,具体使用哪种方式取决于个人习惯和代码风格。