프로그래밍 언어/JAVA(자바)

[자바/java] Set, HashSet 사용법 데이터 삽입, 삭제, 출력

냠냠:) 2020. 9. 1. 01:44

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());
        
    }
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"));
    }
cs
/*출력*/
true
false
728x90

 

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());
    
    }
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());
    }
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());
    }
cs
/*출력*/
4
반응형