Java中的AbstractMapisEmpty()方法示例
AbstractMap类的AbstractMap.isEmpty()方法用于检查地图是否为空。 如果地图中不存在键值对或映射,则该方法返回True,否则返回False。
语法:
AbstractMap.isEmpty()
参数: 该方法不需要任何参数。
返回值: 如果地图为空或不包含任何映射对,则该方法返回boolean true,否则返回boolean false。
下面的程序说明了AbstractMap.isEmpty()方法的工作原理:
程序1: 将字符串值映射到整数键。
// Java code to illustrate the isEmpty() method
import java.util.*;
public class AbstractMap_Demo {
public static void main(String[] args)
{
// 创建空的AbstractMap
AbstractMap<String, Integer>
abs_map = new HashMap<String, Integer>();
// 将int值映射到字符串键
abs_map.put("Geeks", 10);
abs_map.put("4", 15);
abs_map.put("Geeks", 20);
abs_map.put("Welcomes", 25);
abs_map.put("You", 30);
// 显示AbstractMap
System.out.println("The Mappings are: "
+ abs_map);
// 检查Map是否为空
System.out.println("Is the map empty? "
+ abs_map.isEmpty());
}
}
The Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
Is the map empty? false
程序2: 对于空的HashMap
// Java code to illustrate the isEmpty() method
import java.util.*;
public class Abstract_Map_Demo {
public static void main(String[] args)
{
//创建空的AbstractMap
AbstractMap<String, Integer>
abs_map = new HashMap<String, Integer>();
// 显示AbstractMap
System.out.println("The Mappings are: "
+ abs_map);
// 检查Map是否为空
System.out.println("Is the map empty? "
+ abs_map.isEmpty());
}
}
The Mappings are: {}
Is the map empty? true
注意: 可以使用不同数据类型的变化和组合执行任何类型的映射相同的操作。