LinkedHashSet
- LinkedHashSet은 Java의 Set 구현체로, HashSet의 성능에 입력 순서 유지 기능을 추가한 순서 있는 집합입니다.
- 내부적으로 HashMap + Doubly Linked List 구조를 사용하여 요소의 순서를 기억합니다.
주요 특징
자료구조 |
HashMap + 이중 연결 리스트 |
정렬 여부 |
✅ 입력 순서 유지 |
중복 허용 |
❌ (Set의 기본 특성) |
null 허용 |
✅ (단 하나만 허용) |
시간 복잡도 |
add, remove, contains 평균 O(1) |
차이점 |
HashSet보다 약간 느리지만 순서를 기억함 |
대표 메서드
package structure.set.linkedhashset;
import java.util.LinkedHashSet;
public class LinkedHashSetClass {
private final LinkedHashSet<Integer> linkedHashSet;
public LinkedHashSetClass(LinkedHashSet<Integer> linkedHashSet) {
this.linkedHashSet = linkedHashSet;
}
// 집합에 값을 추가합니다.
// 시간 복잡도: O(1)
// 예외 발생: NullPointerException - linkedHashSet이 null인 경우
public LinkedHashSet<Integer> add(int value) {
this.linkedHashSet.add(value);
return this.linkedHashSet;
}
// 집합에서 지정된 값을 제거합니다.
// 시간 복잡도: O(1)
// 예외 발생: NullPointerException - linkedHashSet이 null인 경우
public LinkedHashSet<Integer> remove(int value) {
this.linkedHashSet.remove(value);
return this.linkedHashSet;
}
// 집합에 지정된 값이 포함되어 있는지 확인합니다.
// 시간 복잡도: O(1)
// 예외 발생: NullPointerException - linkedHashSet이 null인 경우
public boolean contains(int value) {
return this.linkedHashSet.contains(value);
}
// 집합의 모든 요소를 제거합니다.
// 시간 복잡도: O(1)
// 예외 발생: NullPointerException - linkedHashSet이 null인 경우
public void clear() {
this.linkedHashSet.clear();
}
// 집합이 비어 있는지 확인합니다.
// 시간 복잡도: O(1)
// 예외 발생: NullPointerException - linkedHashSet이 null인 경우
public boolean isEmpty() {
return this.linkedHashSet.isEmpty();
}
// 집합의 요소 개수를 반환합니다.
// 시간 복잡도: O(1)
// 예외 발생: NullPointerException - linkedHashSet이 null인 경우
public int size() {
return this.linkedHashSet.size();
}
}