检查密钥是否存在

Map<String, String> num = new HashMap<>();
num.put("one", "first");

if (num.containsKey("one")) {
    System.out.println(num.get("one")); // => first
}

地图可以包含空值

对于地图,人们必须不要混淆包含键有价值。例如,HashMaps 可以包含 null,这意味着以下是完全正常的行为:

Map<String, String> map = new HashMap<>();
map.put("one", null);
if (map.containsKey("one")) {
    System.out.println("This prints !"); // This line is reached 
}
if (map.get("one") != null) {
    System.out.println("This is never reached !"); // This line is never reached 
}

更正式的,不能保证 map.contains(key) <=> map.get(key)!=null