본문 바로가기
Programming/Java

[Java] 자바 Set(집합) 인터페이스

by 서현 SEOHYEON 2023. 6. 29.

💚 Set(집합) 인터페이스 특징

① 중복 요소 불허: Set은 중복된 요소를 허용하지 않는다. 동일한 요소를 여러 번 추가하더라도 하나만 유지된다.

② 순서 없음: Set은 요소들의 순서를 보장하지 않는다.

 

- Set의 구현 클래스로는 HashSet, TreeSet, LinkedHashSet 등이 있다. 각 구현 클래스마다 데이터를 다른 방식으로 저장하고 동작한다. HashSet은 해시 테이블을 사용하여 요소를 저장하고, TreeSet은 이진 검색 트리를 사용하여 요소를 정렬한다.

 

 

💚 import

import java.util.Set;

 

 

💚 주요 기본 메서드(요소 추가, 제거...)

반환형 메서드 설명
boolean add(E e) 지정된 요소를 Set에 추가
이미 존재하는 요소라면 추가되지 않는다.
boolean remove(Object o) 지정된 요소를 Set에서 제거
boolean contains(Object o) 지정된 요소가 Set에 존재하는지 확인
int size() Set에 포함된 요소의 개수를 반환
boolean isEmpty() Set이 비어있는지 확인
void clear() Set의 모든 요소를 제거하여 비움

 

 

💚 주요 기본 메서드 사용예시

import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        // HashSet 생성
        Set<String> set = new HashSet<>();

        // add() 메서드를 사용하여 요소 추가
        set.add("Apple");
        set.add("Banana");
        set.add("Orange");
        set.add("Apple"); // 중복 요소이므로 추가되지 않음

        System.out.println("Set elements: " + set); // Set 요소 출력

        // size() 메서드를 사용하여 요소 개수 확인
        System.out.println("Number of elements: " + set.size());

        // contains() 메서드를 사용하여 요소의 존재 여부 확인
        System.out.println("Contains 'Banana': " + set.contains("Banana")); // true
        System.out.println("Contains 'Grape': " + set.contains("Grape")); // false

        // remove() 메서드를 사용하여 요소 제거
        set.remove("Orange");

        // isEmpty() 메서드를 사용하여 Set이 비어 있는지 확인
        System.out.println("Is set empty? " + set.isEmpty()); // false

        // clear() 메서드를 사용하여 Set 비우기
        set.clear();

        System.out.println("Set elements after clearing: " + set); // []

        System.out.println("Is set empty after clearing? " + set.isEmpty()); // true
    }
}

- 실행 결과

Set elements: [Banana, Orange, Apple]
Number of elements: 3
Contains 'Banana': true
Contains 'Grape': false
Is set empty? false
Set elements after clearing: []
Is set empty after clearing? true

 

 

💚 HashSet을 사용해 합집합, 교집합, 차집합 구하기

① 합집합 구하기: addAll() 메서드를 사용

 교집합 구하기: retainAll() 메서드를 사용

 차집합 구하기: removeAll() 메서드를 사용

- 메서드 설명

반환형 메서드 설명
boolean addAll(Collection<? extends E> c) 지정된 컬렉션에 있는 요소들을 현재 집합에 추가한다. (없는 경우만)
boolean retainAll(Collection<?> c) 지정된 컬렉션에 포함된 이 집합의 요소만 유지한다.
boolean removeAll(Collection<?> c) 지정된 컬렉션에 포함된 이 집합의 요소들을 제거한다.

- 예시

import java.util.HashSet;
import java.util.Set;

public class SetOperationsExample {
    public static void main(String[] args) {
        // 첫 번째 Set 생성
        Set<String> set1 = new HashSet<>();
        set1.add("apple");
        set1.add("banana");
        set1.add("orange");
        set1.add("grape");

        // 두 번째 Set 생성
        Set<String> set2 = new HashSet<>();
        set2.add("orange");
        set2.add("grape");
        set2.add("kiwi");

        // 합집합 구하기
        Set<String> union = new HashSet<>(set1);
        union.addAll(set2);
        System.out.println("Union: " + union);

        // 교집합 구하기
        Set<String> intersection = new HashSet<>(set1);
        intersection.retainAll(set2);
        System.out.println("Intersection: " + intersection);

        // 차집합 구하기
        Set<String> difference = new HashSet<>(set1);
        difference.removeAll(set2);
        System.out.println("Difference (set1 - set2): " + difference);
    }
}

- 실행 결과

Union: [kiwi, orange, apple, grape, banana]
Intersection: [orange, grape]
Difference (set1 - set2): [apple, banana]

공식 문서 참고

https://docs.oracle.com/javase/8/docs/api/java/util/Set.html

 

Set (Java Platform SE 8 )

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction. The Set inter

docs.oracle.com

 

댓글