HashMap은 Java 컬렉션 프레임워크 중 가장 많이 사용하는 자료구조 중 하나다.
Key-Value 형태로 데이터를 저장한다.
특징:
hashCode()를 호출하여 해시값을 얻는다.(n-1) & hash).Node 구조:
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
}
| 연산 | 평균 | 최악 |
|---|---|---|
| 조회 (get) | O(1) | O(n) |
| 삽입 (put) | O(1) | O(n) |
| 삭제 (remove) | O(1) | O(n) |
※ 최악의 경우는 모든 Key가 충돌할 때.
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
System.out.println(map.get("two")); // 2
"two"의 hashCode()를 통해 배열 인덱스를 찾고, 빠르게 접근한다.hashCode()와 equals()를 기반으로 Key를 관리한다.ConcurrentHashMap 사용을 추천한다.