1. 程式人生 > >containsKey方法——判斷是否包含指定的鍵名

containsKey方法——判斷是否包含指定的鍵名

Map可以出現在k與v的對映中,v為null的情況 Map集合允許值物件為null,並且沒有個數限制,所以當get()方法的返回值為null時,可能有兩種情況,一種是在集合中沒有該鍵物件,另一種是該鍵物件沒有對映任何值物件,即值物件為null。因此,在Map集合中不應該利用get()方法來判斷是否存在某個鍵,而應該利用containsKey()方法來判斷

public static void main(String[] args) {
 
        Map<String,String> map = new HashMap<String,String>();
        map.put("apple", "新鮮的蘋果"); // 向列表中新增資料
        map.put("computer", "配置優良的計算機"); // 向列表中新增資料
        map.put("book", "堆積成山的圖書"); // 向列表中新增資料
        String key = "book";
        boolean contains = map.containsKey(key);
        if (contains) {
            System.out.println("在Map集合中包含鍵名" + key);
        } else {
            System.out.println("在Map集合中不包含鍵名" + key);
        }
 
    }