티스토리 뷰

반응형

⊙ 문제

 

프로그램에 주어진 2개의 String 타입 배열을 이용해 프로그램의 주석대로 수행하는 프로그램을 작성하시오.

 

public static void main(String[] args) {
     String[] s1 = {"a","b","a","b","c"};
     String[] s2 = {"c"};
     
// 두 배열을 Collections의 addAll() 메서드를 이용해 HashSet 객체로 생성
// 2개의 HashSet 객체를 출력
// 2개의 HashSet 객체가 동일한지 비교한 값을 출력
// s1에 의한 HashSet이 s2에 의한 HashSet 원소를 모두 포함하는지 출력
// 2개의 HashSet 합집합과 교집합을 구해서 출력
}

⊙ 문제 접근 과정

 

주석과 똑같이 구현해주면 된다.

 


 

⊙ 문제 풀이

 

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

public class Main {
    public static void main(String[] args) {
        String[] s1 = {"a","b","a","b","c"};
        String[] s2 = {"c"};

        Set<String> set1 = new HashSet<>();
        Set<String> set2 = new HashSet<>();

        Collections.addAll(set1,s1);
        Collections.addAll(set2,s2);

        System.out.println("set1 : " +set1);
        System.out.println("set1 : " +set2);

        System.out.println("set1과 set2는 같다 : " + set1.equals(set2));
        System.out.println("set1은 set2의 모든 원소를 포함한다 : " + set1.containsAll(set2));

        Set<String> union = new HashSet<>(set1);
        Set<String> intersection = new HashSet<>(set1);

        union.addAll(set2);
        intersection.retainAll(set2);

        System.out.println("합집합 : " + union);
        System.out.println("교집합 : " + intersection);
    }
}

 


⊙ 결과

 


⊙ 마무리

 

 

NONE

 

좋아요는 로그인하지 않아도 누를 수 있습니다!

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함