1. 程式人生 > >集合框架之Map學習

集合框架之Map學習

strong size keys 文章 接口 使用方法 tor entry ash

Map接口的實現類有HashTable、HashMap、TreeMap等,文章學習整理了“ Map和HashMap的使用方法”。
/**
* Map和HashMap的使用方法
*/
public static void mapTest() {
Map<String,String> hashMap = new HashMap<String, String>();
hashMap.put("1","a");
hashMap.put("2","b");
hashMap.put("3","c");
hashMap.put("4","d");
hashMap.put("3","e"); // map中對於鍵相同的,會覆蓋掉前面的值

int i = hashMap.size();
System.out.println(i);

String s = hashMap.get("3");
System.out.println(s);

遍歷方式一:使用Iterator<Map.Entry<String, String>> 遍歷。Map.Entry<String, String>取出的是key-value鍵值對

// 獲取到所有鍵值對形成的映射關系
Set<Map.Entry<String, String>> entry = hashMap.entrySet();
// 獲取叠代器對象
Iterator<Map.Entry<String, String>> iterator = entry.iterator();
while (iterator.hasNext()) {
Map.Entry<String,String> en = iterator.next();
String key = en.getKey(); //獲取到鍵
String value = en.getValue(); //獲取到值
System.out.println(key+"=="+value);
}

遍歷方式二:使用keySet()遍歷
Set<String> keys = hashMap.keySet();
Iterator<String> iterator = keys.iterator(); //獲取叠代器對象
while (iterator.hasNext()) {
String key = iterator.next();
//根據鍵獲取值
String value = hashMap.get(key);
System.out.println(key+"=="+value);
}

}

集合框架之Map學習