Map接口提供了一組可以以鍵-值對(key,value)形式存儲的數據結構。
Map對存入元素只有一個要求,就是鍵(key)不能重複,Map對於key,value要求不是很嚴格,key只要是引用類型即可。通常情況下,使用String和Integer比較多。
Map提供了一個方法用來存入數據:
V put(K k,V v)
該方法的作用是將key-value對存入Map中,因爲Map中不允許出現重複的key,所以若當次存入的key已經在Map中存在,則是替換value操作,而返回值則爲被替換的元素。若此key不存在,那麼返回值爲null。
Map提供了一個獲取value的方法
V get(Object key)
該方法的作用就是根據給定的key去查找Map中對應的value並返回,若當前Map中不包含給定的key,那麼返回值爲null。
Map中的containsKey方法用於檢測當前Map中是否包含給定的key。其方法定義如下:
boolean containsKey(Object key)
public class HashMapDemo {
public static void main(String[] args) {
Map<String, Integer> hashMap = new HashMap<String,Integer>();
hashMap.put("one", 1);
hashMap.put("two", 2);
hashMap.put("three", 3);
hashMap.put("four", 4);
hashMap.put("five", 5);
hashMap.put("six", null);
//獲取Map中key爲two所對應的value
Integer two = hashMap.get("two");
Integer other = hashMap.get("other");
System.out.println(two);
System.out.println(other);
//檢查Map中是否有對應的key
boolean getTwo = hashMap.containsKey("two");
boolean getOther = hashMap.containsKey("other");
System.out.println(getTwo);
System.out.println(getOther);
}
}
運行結果:
2
null
true
false