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