# HashMap TreeMap LinkedHashMap
> HashMap的构造方法 . 合适的遍历 . 复制转换
> HashMap的底层原理
> HashMap, TreeMap, LinkedHashMap 对比
## 1. 通用方法 :
```
put(key, value):存入Map中一个key/value映射
get(Object key):返回指定键所映射的值
remove(Object key):从该Map中删除一个键的映射
containsKey(Object key):是否包含指定的key
testMap.getOrDefault(key, 0));
```
```
Map userMap = new HashMap<>();
userMap.put(122, "a");
userMap.get(122);
userMap.getOrDefault(122, "");
userMap.remove(122);
userMap.containsKey(122);
```
## 2. HashMap的构造方法 :
```
HashMap()
hashMap(int initialCapacity) 指名初始化大小
hashMap(int initialCapacity, float loadFactor) 参数因子:指明在什么情况下会进行扩容
```
## 3. HashMap的Entry结构 :
```
static class Entry<K, V> implements Map.Entry<K, V> {
final K key;
V value;
Entry<K, V> next;
final int hash;
}
```
## 4. Map的4种遍历方式:
注: Map的打印输出不是按照key的固定顺序输出的.
### 1. 利用keySet进行遍历 (速度最慢)
```
for (Integer key : userMap.keySet()) {
System.out.println(key + "***" + userMap.get(key));
}
```
### 2. 利用values进行遍历 (性能最好)
```
for (String v : userMap.values()) {
System.out.println(v);
}
```
### 3.利用entrySet进行遍历 (速度均衡)
```
for (Map.Entry entry:userMap.entrySet()) {
System.out.println(entry.getKey() + "+++" + entry.getValue());
}
```
### 4.利用Iterator迭代器进行遍历 (性能第2)
```
Iterator<Map.Entry<Integer, String> it = userMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = it.next();
System.out.println(entry.getKey() + "+++" + entry.getValue());
}
```
### 5. 性能分析
```
public static Map intputMat() {
Map userMap = new HashMap<>();
String[] str = new String[]{"a","b","b","d","e","f","g","h","m","n"};
String key;
int value;
for (int i = 0; i <= 100000; i++) {
int m = (int)(Math.random()*10);
key = str[m] + i * 100;
value = i;
userMap.put(key, value);
}
return userMap;
}
```
结论 : values 和 Iterator 最快. keySet 最慢.