Map
Map是用來儲存鍵值對的,鍵值的作用和索引相同,他是一個獨一無二的值。
使用put(String,Object)來添加對象
String r1 = "a";
String r2 = "b";
String r3 = "c";
map.put("First",r1);
map.put("second",r2);
map.put("Third",r3);
map.remove("First");//刪除制定鍵值(First)對應的元素。
int size =map.size();//獲悉結構包含多少個元素
boolean isEmpty = map.isEmpty();//判斷是否爲空
使用get(String ,Object),來獲取對象
String d = (String)map.get("second")
HashMap
HashMap類,實現了接口Map,並提供了鍵映射數據結構的完整實現。HashMap由負載係數定義效率,負載係數是一個0.1~1.0的浮點數。越接近1.0,則內存使用率越高,但是查找時間變長。散列映射通過將“當前長度”同“容量和負載係數的乘積”比較來分配內存。如果長度超過乘積,則重新散列(rehash)來增加容量。
創建HashMap:
HashMap hash = new HashMap();//默認的,初始容量爲16,負載係數爲0.75
HashMap hash = new HashMap(20);//初始容量爲20,負載係數爲0.75
HashMap hash = new HashMap(20,0.5F);//初始容量爲20,負載係數爲0.5
HashMap類實現了Map定義的所有抽象方法,還實現了其他一些方法比如:
hash.clear();刪除HashMap中所有的鍵值和元素
boolean isThere = hash.containsValue(r1);//查看是否包括該對象
boolean isThere = hash.containsKey("First");//查找對應鍵值(r1)