import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class CheckIfCollectionIsEmpty {
public static void main(String[] args) {
// 创建一个空的集合
List<String> emptyList = Collections.emptyList();
// 创建一个包含元素的集合
List<String> nonEmptyList = List.of("apple", "banana", "orange");
// 判断集合是否为空
if (isEmpty(emptyList)) {
System.out.println("emptyList 是空的");
} else {
System.out.println("emptyList 不是空的");
}
if (isEmpty(nonEmptyList)) {
System.out.println("nonEmptyList 是空的");
} else {
System.out.println("nonEmptyList 不是空的");
}
}
// 定义一个方法来判断集合是否为空
public static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
}
List
类型的集合,一个是空的 emptyList
,另一个是包含元素的 nonEmptyList
。isEmpty
方法来判断集合是否为空。该方法接收一个 Collection<?>
类型的参数,并返回一个布尔值。如果集合为 null
或者调用 isEmpty()
方法返回 true
,则表示集合为空。希望这段代码和解释对你有帮助!
上一篇:java mockito
下一篇:java八种基本类型
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站