728x90
다음은 HashSet과 TreeSet에 대한 간단한 예제이다.
import java.util.Set;
import java.util.TreeSet;
public class Prac {
public static void main(String[] args) {
//Set<String> set = new HashSet<>();
// 정렬된 원소를 얻고 싶다면 treeSet 구현체를 이용해야 한다.
Set<String> set = new TreeSet<>();
set.add("Carol");
set.add("Alice");
set.add("Dave");
set.remove("Carol");
set.add("Erin");
set.add("Erin"); // 이미 존재한다면 추가되지 않습니
System.out.println(set.size()); // 3
System.out.println(set.contains("Alice")); // true
System.out.println(set.contains("Bob")); // false
set.remove("Bob"); // 없는 원소이기 때문에 삭제가 되지 않습니다.
set.remove("Carol");
System.out.println(set.contains("Carol")); // false;
String[] unorderKeys = set.toArray(new String[set.size()]);
// hashSet이라면 set의 원소들이 정렬된 형태로 반환됩니다.
for (String key : unorderKeys)
System.out.println(key);
}
}728x90
'Java' 카테고리의 다른 글
| 중복된 문자열 제거하기 (indexOf) (0) | 2024.06.06 |
|---|---|
| 자바/Java 재귀함수 Recursive (0) | 2024.03.09 |
| 문자열 (0) | 2024.01.06 |
| 이클립스 초기 화면으로 돌리는 법 (perspective 화면 초기화) (0) | 2023.09.27 |
| [Java] HashMap 활용한 전화번호부 예제 (24-1) (0) | 2023.09.14 |