[toc]
# 一、map概述
map接口實現的是一組key-value<b>鍵值對</b>的組合。map中的每一個成員方法由一個關鍵字(key)和一個值(value)構成。map接口的集合中不能有重復的key出現。
另外,set接口的底層是基于hashmap實現的。<b>set中存儲的值,其實就是map中的key</b>,它們是不允許重復的。
為了更好了解map,需要了解hash算法:[http://www.cnblogs.com/xiohao/p/4389672.html](http://www.cnblogs.com/xiohao/p/4389672.html)
已知的常用map實現類有:hashmap、hashtable、linkedhashmap、treemap
## 1-1 map的映射的特點
1.一個映射不能包含重復的鍵;
2.每個鍵最多只能映射一個值;
3.鍵(key)只允許一個空值,值(value)可以有多個空值
4.map是無序的
## 1-2 map的API
這里需要注意的是map中添加元素用的是put方法

# 二、hashmap
## 2-1 hashmap初始化
hashmap實現了map、clonemap、serializable三個接口,并且繼承自abstractmap類。
hashmap基于<b>hash數組</b>實現,若key的hash值相同則使用鏈表的方式進行存儲。
新建一個hashmap時,默認的話為初試一個大小為16,負載因子為0.75的空的hashmap
~~~
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
~~~
## 2-2 hashmap常用API
### get(Object key)
get方法是返回指定鍵所映射的值,返回的是value值。
~~~
value=hashmap.get(key);//一般在遍歷循環里寫
~~~
### keySet()
返回此映射中所包含的鍵(key)的 Set 視圖。返回值為一個set集合
~~~
Set<E> set = map.keySet();
~~~
## 2-3 遍歷hashmap
1.使用for循環
~~~
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("白日鼠", "白勝");
map.put("豹子頭", "林沖");
map.put("小諸葛", "富安");
//1.獲取一個map集合的key的set集合
Set<String> strings = map.keySet();
//2.遍歷map集合,通過上一步獲取的set集合遍歷的key找出value
for(String key:strings){
String value = map.get(key);
System.out.println(key+"-->"+value);
}
}
~~~
2.使用迭代器
~~~
//1.先拿到map的所有key值
Set<String> set = map.keySet();
//2.把key值傳入迭代器
Iterator<String> iterator = set.iterator();
String key;
String value;
while(iterator.hasNext()){
key=iterator.next();
value=map.get(key);
System.out.println(key +"-->"+value);
}
~~~