ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Set 계열의 Collection / Set / HashSet / TreeSet / 2019-12-09
    JAVA 2020. 1. 14. 17:47
    728x90
    728x90

    Set 계열은 순서 없이 데이터를 넣는 형태

    => 동일한 데이터를 넣으면 구분 할 수 X

    => 데이터의 중복 허용 X

     

    HashSet과 TreeSet가 주로 사용됨

     - TreeSet은 정렬기능이 있음

     

    Set 계열은 순서(인덱스)가 없기 때문에 iterator()가 반환하는 Iterator 객체를 사용함

     - Iterator의 주요 메서드

    메서드 명 선언부와 설명
    hasNext() boolean hasNext()     가져올 다음 요소가 있는지 여부를 리턴한다
    next() E next()                   가져올 다음 요소가 있다면 그 요소를 리턴한다
    remove() void remove()           현재 위치의 요소를 삭제한다

     

    HashSet의 기본 문법

    HashSet set = new HashSet();
    System.out.println("Set객체에 저장된 요소 개수 "  + set.size());
    System.out.println("Set객체에 저장된 요소 개수 "  + set.isEmpty());

    데이터 추가 후 출력

    set.add(1);
    set.add("TWO");
    set.add(3.14);
    System.out.println("Set객체에 저장된 요소 개수 "  + set.size());
    System.out.println("Set객체에 저장된 요소 개수 "  + set.isEmpty());
    System.out.println("Set객체에 저장된 모든 요소 출력 : " + set);

    <결과코드>

    Set객체에 저장된 요소 개수 0
    Set객체에 저장된 요소 개수 true
    Set객체에 저장된 요소 개수 3
    Set객체에 저장된 요소 개수 false
    Set객체에 저장된 모든 요소 출력 : [1, 3.14, TWO]

     

    Set계열은 데이터 중복 저장이 불가하다

    System.out.println("정수 1추가 가능한가? : " + set.add(1));

    <결과코드>

    정수 1추가 가능한가? : false

     

    Iterator() 사용법

    Iterator iter = set.iterator();
      while(iter.hasNext()) {
      Object o = iter.next();
      System.out.println(o);
    }

    <결과코드>

    1
    3.14
    TWO

     

    equals() 메서드와 containsAll() 메서드

    Object[] arr = set.toArray();
    System.out.println(Arrays.toString(arr));
    
    // set의 데이터를 set2에 복사하기
    Set set2 = new HashSet();
    for (int i = 0; i < arr.length; i++) {
    	set2.add(arr[i]);
    }
    System.out.println("set, set2의 주소값이 같은가? " + (set == set2));		// false 출력
    System.out.println("set, set2의 모든 요소가 같은가? " + set.equals(set2));  // true 출력
    // set2에 데이터 추가
    set2.add(10);	
    // containsAll() 메서드를 통해 데이터를 모두 포함하고 있는지 알 수 있음
    System.out.println(set.containsAll(set2));	// false 출력
    System.out.println(set2.containsAll(set));	// true 출력

     

    자동 정렬 기능이 있는 TreeSet()

    // 무작위로 데이터 입력
    Set set3 = new TreeSet();
    set3.add(1);
    set3.add(24);
    set3.add(8);
    set3.add(56);
    set3.add(4);

    <결과코드>

    [1, 4, 8, 24, 56]

     

    객체 초기화

    set3.clear();
    System.out.println("set3 객체 초기화");
    System.out.println("set3 : " + set3);

    <결과코드>

    set4 : []
    728x90
    728x90
Designed by Tistory.