Java中的HashMap
HashMap类的java.util.HashMap.isEmpty() 方法用于检查映射的空白。如果HashMap中没有键值对或映射,则该方法返回True,否则返回False。
句法:
Hash_Map.isEmpty()
参数:该方法不接受任何参数。
返回值:如果映射为空或者不包含任何映射对,则该方法返回boolean true,否则为boolean false。
下面的程序说明了java.util.HashMap.isEmpty()方法的工作原理
HashMap.isEmpty()程序1:将字符串值映射到整数键。
// Java code to illustrate the isEmpty() method
import java.util.*;
public class Hash_Map_Demo {
public static void main(String[] args)
{
// Creating an empty HashMap
HashMap hash_map = new HashMap();
// Mapping int values to string keys
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);
// Displaying the HashMap
System.out.println("The Mappings are: " + hash_map);
// Checking for the emptiness of Map
System.out.println("Is the map empty? " + hash_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 Hash_Map_Demo {
public static void main(String[] args)
{
// Creating an empty HashMap
HashMap hash_map = new HashMap();
// Displaying the HashMap
System.out.println("The Mappings are: " + hash_map);
// Checking for the emptiness of Map
System.out.println("Is the map empty? " + hash_map.isEmpty());
}
}
输出:
The Mappings are: {}
Is the map empty? true
注意:对于具有不同数据类型的变体和组合的任何类型的映射,都可以执行相同的操作。