[Java] Set, HashSet 사용법 데이터 삽입, 삭제, 출력2021. 11. 4. 10:52
출처: https://tosuccess.tistory.com/145
Set이란?
자바 컬렉션에 HashSet은 Set 인터페이스의 구현 클래스다. Set은 한국말로는 "집합"이고,
따로 저장 순서를 유지하지는 않는다. 또한 중복 값을 허용하지 않는다는 특징을 갖고 있다.
*순서를 유지하고 싶으면 LinkedHashSet 클래스를 사용하면 된다.
1. 객체 선언 - new HashSet<>();
1 | Set<String> set = new HashSet<String>(); | cs |
2. 데이터 삽입 - set.add()
1 2 3 4 5 6 |
Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("pyopyo"); set.add("kiwi"); |
cs |
3. 데이터 삭제 - set.remove(object e);
1 2 3 4 5 6 7 8 |
Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("pyopyo"); set.add("kiwi"); set.remove("apple"); |
cs |
4. 데이터 출력
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public static void main(String args[]) { Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("pyopyo"); set.add("kiwi"); Iterator<String> iterSet = set.iterator(); while(iterSet.hasNext()) { System.out.print(iterSet.next() +" "); } System.out.println(); System.out.println(set.toString()); } Colored by Color Scripter |
cs |
/*출력*/
banana apple kiwi pyopyo
[banana, apple, kiwi, pyopyo]
Iterator을 사용하는 경우는 각 데이터를 조작할 때 사용한다.
toString() 경우에는 단순히 set에 어떤 데이터가 포함되어있는지 확인할 때 사용한다.
5. 값 포함 유무 - set.contains(object e)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static void main(String args[]) { Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("pyopyo"); set.add("kiwi"); System.out.println(set.contains("apple")); System.out.println(set.contains("hi")); } Colored by Color Scripter |
cs |
/*출력*/
true
false
6. 전체 데이터 삭제 - set.clear()
1 2 3 4 5 6 7 8 9 10 11 12 |
public static void main(String args[]) { Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("pyopyo"); set.add("kiwi"); set.clear(); System.out.println(set.toString()); } Colored by Color Scripter |
cs |
/*출력*/
[]
7. 값 존재 유무 - set.isEmpty()
1 2 3 4 5 6 7 8 9 10 |
public static void main(String args[]) { Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("pyopyo"); set.add("kiwi"); System.out.println(set.isEmpty()); } Colored by Color Scripter |
cs |
/*출력*/
false
8. Set 데이터 크기 - set.size()
1 2 3 4 5 6 7 8 9 10 |
public static void main(String args[]) { Set<String> set = new HashSet<String>(); set.add("apple"); set.add("banana"); set.add("pyopyo"); set.add("kiwi"); System.out.println(set.size()); } Colored by Color Scripter |
cs |
/*출력*/
4
출처: https://tosuccess.tistory.com/145 [EI_HJ]
'Development > Java' 카테고리의 다른 글
[Java] 조건 삼항 연산자 기본 (원리) ?: (0) | 2021.08.10 |
---|---|
[Java] Java 스트림 Stream 총정리 (0) | 2021.08.10 |
[Java] Java 스트림 Stream 총정리 (0) | 2021.08.10 |
[Java] Hash - MD5와 SHA256해시(Hash)와 암호화(Encryption)의 차이 (0) | 2021.08.10 |
[Java] MD5 Hashing in Java (0) | 2021.08.10 |