一、Map
key不允许重复,和HashSet一样。 可以为null,但是只能包含一个null
value允许重复,可以包含多个null
二、HashMap
- 具体结构在前面HashSet已经介绍完毕
- 是线程不安全的
1. 数据结构
private static void method01() {
HashMap<String, String> map = new HashMap<>();
map.put("name", "erick");
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String value = entry.getValue();
}
}

static final float DEFAULT_LOAD_FACTOR = 0.75f;
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
- Node<K,V> implements Map.Entry<K,V>
- k为存入的key, v为对应的value
- 某个节点的元素,如果是之前是树,后续当树的节点减少到6个,就会
重新变成链表
- 重复元素时候,替换对应的value,key不变
2. 遍历方式
package com.erick.feature.collection.d02;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Demo05 {
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<>();
map.put("name", "erick");
map.put("age", "11");
method03(map);
}
private static void method01(Map<String, String> map) {
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String value = entry.getValue();
}
}
private static void method02(Map<String, String> map) {
Set<Map.Entry<String, String>> entries = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
String key = next.getKey();
String value = next.getValue();
}
}
private static void method03(Map<String, String> map) {
Collection<String> values = map.values();
for (String value : values) {
System.out.println(value);
}
}
private static void method04(Map<String, String> map) {
Collection<String> values = map.values();
Iterator<String> iterator = values.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
}