Notice
Recent Posts
Recent Comments
«   2024/09   »
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
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

HashSet 1 본문

Java/JAVA2

HashSet 1

빌드이너프 2023. 7. 16. 21:11

HashSet - 순서 X, 중복 X 

HashSet

Set 인터페이스를 구현한 대표적인 컬렉션 클래스

순서를 유지하려면, LinkedHashSet 클래스를 사용하면 된다

 

TreeSet

범위 검색과 정렬에 유리한 컬렉션 클래스

HashSet보다 데이터 추가, 삭제에 시간이 더 걸림

 

HashSet 주요 메서드

HashSet()
HashSet(Collection c)
HashSet(int initialCapacity)
HashSet(int initialCapacity, float liadFactor)
boolean add(Object o)
boolean addAll(Collection c)
boolean remove(Object o)
boolean removeAll(Collection c)
boolean retainAll(Collection c)
void clear()
boolean contains(Obejct o)
boolean containsAll(Collection c)
Iterator iterator()
boolean isEmpty()
int size()
Object[] toArray()
Object[] toArray(Object[] a)

 

코드

1이 2개 나옴

"1": 문자열

1: Integer 객체

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetTest {
    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++) {
            set.add(objArr[i]);	// HashSet에 objArr의 요소들을 저장
        }
        // HashSet에 저장된 요소들을 출력
        System.out.println(set);

        // HashSet에 저장된 요소들을 출력(Iterator이용)
        Iterator it = set.iterator();

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

[1, 1, 2, 3, 4]
1
1
2
3
4

 

코드

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

public class HashSetTest2 {
    public static void main(String[] args) {
        Set set = new HashSet();
        
        // set의 크기가 6보다 작은 동안 1~45 사이의 난수를 저장
        for (int i = 0; set.size() < 6 ; i++) {
            int num = (int)(Math.random()*45) + 1;
            // set.add(new Integer(num));
            set.add(num);
        }
        
        // set은 정렬불가능하기 때문에 set을 list로 옮겨서 정렬한다
        List list = new LinkedList(set); // LinkedList(Collection c)
        Collections.sort(list);          // Collections.sort(List list)
        System.out.println(list);
    }
}

[8, 9, 11, 12, 14, 18]

'Java > JAVA2' 카테고리의 다른 글

TreeSet  (0) 2023.07.19
HashSet 2  (0) 2023.07.17
Arrays  (0) 2023.07.14
Iterator, ListIterator, Enumeration | Map과 Iterator  (0) 2023.07.13
Stack & Queue  (0) 2023.07.07