Java判断Map是否为空:isEmpty()方法详解及示例
要判断一个Map是否为空,可以使用Map的'isEmpty()'方法。这个方法会返回一个布尔值,指示Map是否为空。
以下是一个使用Java语言判断Map是否为空的示例代码:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// 创建一个空的HashMap
Map<String, Integer> map = new HashMap<>();
// 判断Map是否为空
if (map.isEmpty()) {
System.out.println('Map is empty');
} else {
System.out.println('Map is not empty');
}
}
}
输出结果为:'Map is empty',表示Map为空。
如果要判断的是一个已有元素的Map,只需在创建Map对象时添加元素即可。例如:
Map<String, Integer> map = new HashMap<>();
map.put('key', 1);
此时,判断结果为:'Map is not empty',表示Map不为空。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/qd2E 著作权归作者所有。请勿转载和采集!