Post

[자료구조] 집합

#naver-import

원문: https://blog.naver.com/qoxmfaktmxj/223754133511

집합(Set)

순서 없이 저장

같은 값 원소 중복 X (여러번 입력해도 하나만 유지)

배열,리스트와 다르게 인덱스 접근 불가

다른 자료구조와 조합하여 순서,색인,정렬이 있는 집합 만들 수 있음

집합 연산 ( 합집합(Union), 교집합(Inerserction), 차집합(Difference), 대칭 차집합(Symmetric))

삽입 :add , 삭제 :remove, 확인 :contains

합집합 : addAll, 교집합 : retainAll , 차집합 :removeAll [ Collection 인터페이스 상속받아 사용 ]

public static void main(String[] args){ //Set : Genereic Set<String> set = new HashSet<>();

set.add(“one”); set.add(“two”); set.add(“three”); System.out.println(set); //정렬안됨 set.add(“one”); System.out.println(set); //변화 X set.remove(“three”); for (String a :set){ System.out.println(a); }

Set<String> set1 = new HashSet<>(); Set<String> set2 = new HashSet<>(); set1.add(“one”); set1.add(“three”); set1.add(“two”); set1.add(“four”);

set2.add(“one”); set2.add(“two”); set2.add(“three”);

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 : “ + difference); }

IT 개발현장에서 쓰이는 부분**

댓글