자료구조

HashMap - Java

Stitchhhh 2025. 5. 1. 12:35

HashMap

  • HashMap은 Java의 가장 일반적인 Map 구현체로, 키-값 쌍(Key-Value Pair)을 저장하며, 내부적으로 해시 테이블(Hash Table) 기반으로 작동합니다.
  • 정렬 순서나 삽입 순서를 유지하지 않지만, 탐색 및 삽입 속도가 매우 빠릅니다.

주요 특징

자료구조 해시 테이블 (HashTable)
정렬 여부 ❌ 없음 (순서 보장 X)
삽입 순서 유지
null 허용 ✅ (Key 1개 + Value 여러 개 허용)
시간 복잡도 평균 O(1) (삽입, 삭제, 조회)
특징 가장 빠르며, 가장 자주 사용됨. 순서가 중요하지 않을 때 사용

대표 메서드

package structure.map.hashmap;

import java.util.Collection;
import java.util.HashMap;

public class HashMapClass {

    private final HashMap<Integer, String> hashMap;

    public HashMapClass(HashMap<Integer, String> hashMap) {
        this.hashMap = hashMap;
    }

    // 맵에 키-값 쌍을 추가하거나 업데이트합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - hashMap이 null인 경우
    public HashMap<Integer, String> put(int key, String value) {
        this.hashMap.put(key, value);
        return this.hashMap;
    }

    // 지정된 키에 해당하는 값을 반환합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - hashMap이 null인 경우
    public String get(int key) {
        return this.hashMap.get(key);
    }

    // 지정된 키에 해당하는 항목을 제거합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - hashMap이 null인 경우
    public HashMap<Integer, String> remove(int key) {
        this.hashMap.remove(key);
        return this.hashMap;
    }

    // 맵에 지정된 키가 포함되어 있는지 확인합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - hashMap이 null인 경우
    public boolean containsKey(int key) {
        return this.hashMap.containsKey(key);
    }

    // 맵에 지정된 값이 포함되어 있는지 확인합니다.
    // 시간 복잡도: O(n)
    // 예외 발생: NullPointerException - hashMap이 null인 경우
    public boolean containsValue(String value) {
        return this.hashMap.containsValue(value);
    }

    // 맵의 모든 요소를 제거합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - hashMap이 null인 경우
    public void clear() {
        this.hashMap.clear();
    }

    // 맵이 비어 있는지 확인합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - hashMap이 null인 경우
    public boolean isEmpty() {
        return this.hashMap.isEmpty();
    }

    // 맵의 요소 개수를 반환합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - hashMap이 null인 경우
    public int size() {
        return this.hashMap.size();
    }

    // 지정된 키가 존재하면 해당 값을, 없으면 기본값을 반환합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - hashMap이 null인 경우
    public String getOrDefault(int key, String defaultValue) {
        return this.hashMap.getOrDefault(key, defaultValue);
    }

    // 맵의 모든 값을 Collection 형태로 반환합니다.
    // 시간 복잡도: O(n)
    // 예외 발생: NullPointerException - hashMap이 null인 경우
    public Collection<String> values() {
        return this.hashMap.values();
    }
}

'자료구조' 카테고리의 다른 글

TreeMap - Java  (4) 2025.05.01
LinkedHashMap - Java  (2) 2025.05.01
TreeSet vs HashSet vs LinkedHashSet  (10) 2025.04.30
LinkedHashSet - Java  (0) 2025.04.30
HashSet - Java  (0) 2025.04.30