/ JAVAJUNGSUK

Ch11-34~36. HashSet

자바의 정석 기초편

0. 목차



Chapter11. 컬렉션 프레임웍

Ch11 - 34. HashSet

Ch11 - 35. HashSet 예제1

Ch11 - 36. HashSet 예제2



Ch11 - 34. HashSet


▶ HashSet이란?

▷ Set 구현 → (저장)순서 허용X, 중복 허용X
▷ (저장)순서 유지하려면, LinkedHashSet 클래스 사용


▶ TreeSet이란?

▷ 범위 검색과 정렬에 유리한 컬렉션 클래스
  • 범위 : from ≤ 범위 < to
▷ HashSet보다 데이터 추가/삭제 시간이 오래 걸림


▶ HashSet의 주요 메서드

▷ HashSet()
  • 생성자
▷ HashSet(Collection c)
  • 지정 된 Collection의 모든 객체 저장
▷ HashSet(int initialCapacity)
  • 초기 용량 저장
  • 보통 사용량의 2배
▷ HashSet(int initialCapacity, float loadFactor)
  • 초기 용량 저장
  • loadFactor : 언제 사용량의 2배로 늘릴 것인지
    ex) loadFactor가 80%이상 찼을 때 ×2
▷ boolean add(Object o)
  • 지정 된 객체(o) 추가
▷ boolean addAll(Collection c)
  • 지정 된 Collection 추가
  • 합집합
▷ boolean remove(Object o)
  • 지정 된 객체(o) 삭제
▷ boolean removeAll(Collection c)
  • 지정 된 Collection 삭제
  • 교집합
▷ void clear()
  • 모두 삭제
▷ boolean retainAll(Collection c)
  • 조건부 삭제
  • 차집합
▷ boolean contains(Object o)
  • 지정 된 객체(o) 포함 여부 반환
  • 포함 - true, 미포함 - false
▷ boolean containsAll(Collection c)
  • 지정 된 Collection 모두 포함 여부 반환
  • 포함 - true, 미포함 - false
▷ Iterator iterator()
  • 읽기
▷ boolean isEmpty()
  • 공실 여부 확인
▷ int size()
  • 저장 된 객체 수
▷ Object[] toArray()
  • 저장 된 객체를 객체 배열로 반환
▷ Object[] toArray(Object[] a)
  • 저장 된 객체를 객체 배열로 반환



Ch11 - 35. HashSet 예제1


▶ Object[]에 “1”, 1, “2”, “2”, “3”, “3”, “4”, “4”, “4” 저장

▷ 1 = new Integer(1)
Object[] objArr = {"1", new Integer(1), "2", "2", "3", "3", "4", "4", "4"};


▶ HashSet에 objArr[] 넣기

▷ add()
Set set = new HashSet();
		
for (int i = 0; i < objArr.length; i++) {
    set.add(objArr[i]);
    
    System.out.println(set);
}

// console
[1]
[1, 1] // 1은 왜 중복? → "1" ≠ 1
[1, 1, 2]
[1, 1, 2]
[1, 1, 2, 3]
[1, 1, 2, 3]
[1, 1, 2, 3, 4] // HashSet : 중복 허용X
[1, 1, 2, 3, 4] // HashSet : 중복 허용X
[1, 1, 2, 3, 4] // HashSet : 중복 허용X


▶ set을 Iterator로 읽기

▷ iterator에 읽을 거리 넣어주기, hasNext(), next()
Iterator it = set.iterator();

while (it.hasNext()) {
    System.out.println(it.next());
}

// console
1
1
2
3
4


▶ 전체

public static void main(String[] args) {
    Object[] objArr = {"1", new Integer(1), "2", "2", "3", "3", "4", "4", "4"};
    
    Set set = new HashSet();
    
    for (int i = 0; i < objArr.length; i++) {
        System.out.print(set);
        
        if(set.add(objArr[i]) == true) {
            set.add(objArr[i]);
            System.out.println(" -" + (objArr[i]) + "-X-OK→ " + set);
        } else {
            System.out.println(" -" + (objArr[i]) + "-O-ERROR→ " + set);
        }
    }
    
    Iterator it = set.iterator();
    
    System.out.print("set : " );
    
    while (it.hasNext()) {
        System.out.print(it.next() + " ");
    }
}

// console
[] -1-X-OK [1]
[1] -1-X-OK [1, 1]
[1, 1] -2-X-OK [1, 1, 2]
[1, 1, 2] -2-O-ERROR [1, 1, 2]
[1, 1, 2] -3-X-OK [1, 1, 2, 3]
[1, 1, 2, 3] -3-O-ERROR [1, 1, 2, 3]
[1, 1, 2, 3] -4-X-OK [1, 1, 2, 3, 4]
[1, 1, 2, 3, 4] -4-O-ERROR [1, 1, 2, 3, 4]
[1, 1, 2, 3, 4] -4-O-ERROR [1, 1, 2, 3, 4]
set : 1 1 2 3 4 



Ch11 - 36. HashSet 예제2


▶ HashSet에 6개의 난수(1 ~ 45) 넣기

▷ (Math.random * 45) + 1
Set set = new HashSet();
		
for (int i = 0; set.size() < 6; i++) {
    int num = (int)(Math.random()*45) + 1;
    set.add(num);
}

▶ set 정렬

▷ 정렬 : 순서 유지 → set은 순서 유지 불가 → set 정렬 불가
▷ set → list 변경 후 정렬
public static void main(String[] args) {
    Set set = new HashSet();
    
    for (int i = 0; set.size() < 6; i++) {
        int num = (int)(Math.random()*45) + 1;
        set.add(num);
    }
    
    System.out.print("set : " + set);
    
    List list = new LinkedList(set);
    
    Collections.sort(list);
    System.out.println(" -정렬→ " + list);
}

// console
set : [16, 39, 26, 27, 14, 31] -정렬→ [14, 16, 26, 27, 31, 39]