개요[ | ]
- 각 값이 겹치지 않고 고유한 값을 가진 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
CPU
1.6s
MEM
78M
1.0s
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();
}
}
합집합 결과 1 2 3 4 5 교집합 결과 차집합 결과 1 2 3 4 5
편집자 175.197.192.184 에어컨 Jmnote
로그인하시면 댓글을 쓸 수 있습니다.