자료구조

HashSet - Java

Stitchhhh 2025. 4. 30. 13:20

HashSet

  • HashSet은 Java에서 제공하는 Set 인터페이스의 구현체로, 중복을 허용하지 않고, 저장된 순서를 유지하지 않으며,
    빠른 검색/추가/삭제 성능을 갖춘 자료구조입니다.

주요 특징

자료구조 내부적으로 HashMap 기반
정렬 여부 ❌ (저장 순서 보장 X)
중복 허용 ❌ (Set의 기본 특성)
null 허용 ✅ (단 하나의 null 값만 허용)
시간 복잡도 대부분의 연산은 평균 O(1)

대표 메서드

package structure.set.hashset;

import java.util.HashSet;

public class HashSetClass {

    private final HashSet<Integer> hashSet;

    public HashSetClass(HashSet<Integer> hashSet) {
        this.hashSet = hashSet;
    }

    // 집합에 값을 추가합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - hashSet이 null인 경우
    public HashSet<Integer> add(int value) {
        this.hashSet.add(value);
        return this.hashSet;
    }

    // 집합에서 지정된 값을 제거합니다.
    // 시간 복잡도: O(1)
    // 예외 발생: NullPointerException - hashSet이 null인 경우
    public HashSet<Integer> remove(int value) {
        this.hashSet.remove(value);
        return this.hashSet;
    }

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

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

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

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

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

TreeSet vs HashSet vs LinkedHashSet  (10) 2025.04.30
LinkedHashSet - Java  (0) 2025.04.30
TreeSet - Java  (0) 2025.04.30
PriorityQueue - Java  (6) 2025.04.29
ArrayDeque - Java  (14) 2025.04.28