Java Set

Jmnote (토론 | 기여)님의 2021년 10월 12일 (화) 22:08 판 (Jmnote님이 Java set 문서를 Java Set 문서로 이동했습니다)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

개요[ | ]

각 값이 겹치지 않고 고유한 값을 가진 collection 이다
합집합, 차집합, 교집합 연산이 가능하다
  • hash set 예제
Java
CPU
1.3s
MEM
77M
0.8s
Copy
import java.util.HashSet;

public class Main {
  public static void main(String[] args) {

    HashSet<Integer> numbers = new HashSet<Integer>();

    numbers.add(4);
    numbers.add(7);
    numbers.add(8);

    for(int i = 1; i <= 10; i++) {
      if(numbers.contains(i)) {
        System.out.println(i + " was found in the set.");
      } else {
        System.out.println(i + " was not found in the set.");
      }
    }
  }
}
1 was not found in the set.
2 was not found in the set.
3 was not found in the set.
4 was found in the set.
5 was not found in the set.
6 was not found in the set.
7 was found in the set.
8 was found in the set.
9 was not found in the set.
10 was not found in the set.

  • 집합 연산 예제
Java
Copy
//Please don't change class name 'Main'
import java.util.ArrayList;
import java.util.HashSet;

import java.util.Iterator;

class Main {

    public static void main(String[] args) {
        HashSet<Integer> A = new HashSet<Integer>();
        A.add(1);
        A.add(2);
        A.add(3);

        HashSet<Integer> B = new HashSet<Integer>();
        B.add(3);
        B.add(4);
        B.add(5);

        HashSet<Integer> C = new HashSet<Integer>();
        C.add(1);
        C.add(2);


        A.addAll(B);
		System.out.print("합집합 결과 ");
		for(int n : A) System.out.print(n + " ");
		System.out.println();
        B.retainAll(C);
		System.out.print("교집합 결과 ");
		for(int n : B) System.out.print(n + " ");
		System.out.println();
        A.removeAll(B);
		System.out.print("차집합 결과 ");
		for(int n : A) System.out.print(n + " ");
		System.out.println();
    }
}
Loading
편집자 175.197.192.184 에어컨 J Jmnote