Map介面containsKey與get方法區別
阿新 • • 發佈:2019-01-04
Map集合允許value為null,並且沒有個數限制,所以當get()方法的返回值為null時,可能有兩種情況,一種是在集合中沒有該鍵物件,另一種是該鍵物件沒有對映任何值物件,即值物件為null。因此,在Map集合中不應該利用get()方法來判斷是否存在某個鍵,而應該利用containsKey()方法來判斷,例如下面的例子。
下面的程式碼首先建立一個由HashMap類實現的Map集合,並依次向Map集合中新增一個值物件為null和“馬先生”的對映;然後分別通過get()和containsKey()方法執行這兩個鍵物件;最後執行一個不存在的鍵物件。關鍵程式碼如下:
import java.util.HashMap; import java.util.Map; public class TestMapKey { public static void main(String[] args) { Map<Integer, String> map = new HashMap<Integer, String>(); map.put(220180, null); map.put(220181, "馬先生"); System.out.println("get()方法的返回結果:"); System.out.print("------ " + map.get(220180)); System.out.print(" " + map.get(220181)); System.out.println(" " + map.get(220182)); System.out.println("containsKey()方法的返回結果:"); System.out.print("------ " + map.containsKey(220180)); System.out.print(" " + map.containsKey(220181)); System.out.println(" " + map.containsKey(220182)); } }
執行結果如下:
get()方法的返回結果:
------ null 馬先生 null
containsKey()方法的返回結果:
------ true true false
結論:Map集合中不應該利用get()方法來判斷是否存在某個鍵,因為可能map的key值存在但value的值為null