檢查金鑰是否存在

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