Set Collection
저장 순서를 유지하는 List와 다르게 Set은 저장 순서가 유지되지 않고, 객체의 중복 저장이 불가능하며, 하나의 null만 저장할 수 있다. 순서가 유지되지 않기 때문에 당연히 index로 데이터 접근이 불가능하다.
Set 인터페이스를 구현한 클래스
- HashSet
- TreeSet
- LinkedHashSet
HashSet
순서대로 입력되지 않고, 일정하게 유지되는 것이 특징이고, 객체의 중복을 허용하지 않는다.
사용 예제)
import java.util.HashSet;
import java.util.Iterator;
class HashSet {
public static void main(String[] args) {
// Integer 담는 HashSet
HashSet<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
set.add(1);
set.remove(2);
System.out.println(set); // [1, 3]
// Iterator로 하나씩 출력 1 3
Iterator iter = set.iterator();
while(iter.hasNext()) {
System.out.print(iter.next() + " ");
}
}
TreeSet
순서대로 입력되지 않고, 일정하게 유지되는 것이 특징이고, 객체의 중복을 허용하지 않는다. HashSet과 달리 이진 탐색 트리(BinarySearchTree) 구조로 이루어져 있어서 기본적으로 오름차순으로 데이터를 정렬한다.
- BST 구조이기 때문에 HashSet에 비해 추가/삭제에는 시간이 좀 더 걸리지만 검색/정렬에는 유리하다.
public static void main(String[] args) {
Set<Integer> set = new TreeSet<Integer>();
set.add(4); // 데이터 추가
set.add(2);
set.add(1);
set.add(3);
set.add(1);
set.add(3);
Iterator<Integer> it = set.iterator(); // 반복자 생성
while (it.hasNext()) {
System.out.println(it.next());
}
}
LinkedHashSet
- 객체를 중복해서 저장할 수 없고 하나의 null 값만 저장할 수 있다.
- HashSet과 동일한 구조를 가지지만 저장 순서가 유지된다는 차이점이 있다.
public static void main(String[] args) {
Set<String> set = new LinkedHashSet<String>();
set.add("1");
set.add("1");
set.add("two");
set.add("3");
set.add("4");
set.add("five");
Iterator<String> it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
[출처]
https://coding-factory.tistory.com/554
https://coding-factory.tistory.com/555
https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=heartflow89&logNo=220994601249
'Algorithm > 자료구조' 카테고리의 다른 글
[자료구조] LinkedList (0) | 2022.02.16 |
---|---|
[자료구조] 배열 (Array), 큐(Queue), 스택(Stack) (0) | 2022.02.15 |