//집합 자료형에는 HashSet, TreeSet, LinkedHashSet 등이 있다.
import java.util.Arrays;
import java.util.HashSet;
public class Sample5 {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>(Arrays.asList("H", "e", "l", "l", "o"));
System.out.println(set); // [e, H, l, o] 출력
//리스트, 배열에는 순서가 있지만 set, map에는 순서가 없음. set에는 중복도 없음.
HashSet<Integer> s1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6));
HashSet<Integer> s2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 9));
//제네릭스로 정수형을 지정할 때, int가 아닌 Integer를 썼음을 알 수 있다.
HashSet<Integer> intersection = new HashSet<>(s1);
//교집합 하면 객체가 바뀌어버리기 때문에 복사해서 교집합 해야한다. intersection이라는 새 집합 만듦.
intersection.retainAll(s2);
//교집합 = retainAll.
System.out.println(intersection);
HashSet<Integer> union = new HashSet<>(s1);
union.addAll(s2);
System.out.println(union);
//합집합 = addAll.
HashSet<Integer> substract = new HashSet<>(s1);
union.removeAll(s2);
System.out.println(substract);
//차집합 = removeAll
HashSet<String> tryadd = new HashSet<>();
tryadd.add("Jump");
tryadd.add("To");
tryadd.add("Java");
tryadd.addAll(Arrays.asList("to", "java")); //--여러 값을 한꺼번에 추가함.
tryadd.remove("to");
System.out.println(tryadd);
//TreeSet: 값을 오름차순으로 정렬한다. LinkedHashSet:깂을 입력한 순서대로 저장한다.
'JAVA' 카테고리의 다른 글
[점프 투 자바] 자료형 - 형 변환 (0) | 2024.02.01 |
---|---|
[점프 투 자바] 자료형 - 상수 집합(enum) (1) | 2024.02.01 |
[점프 투 자바] 자료형 - 맵(map) (0) | 2024.02.01 |
[점프 투 자바] 자료형 - 리스트(ArrayList) (0) | 2024.02.01 |
[점프 투 자바] 자료형 - 문자열(String) (1) | 2024.01.30 |