Java/기본

[java] java set , HashSet 자료구조

vmpo 2021. 10. 4. 03:05

 

java의 자료 구조중 Set interface에 대해 확인해보겠습니다.

 

set 인터페이스를 구현한 대표적인 클래스는 Hashset과 Treeset이 있습니다. 이중 자주 사용하는 HashSet 샘플을 확인해보겠습니다.

 

Set은 아래와 같은 특성이 있습니다.

 

# 중복을 허용하지 않는다.

# List와 달리 순서를 보장하지 않는다.

 

1.  중복을 허용하지 않음.

public class SetTester {

  public static void main(String[] args) {

    Set<Integer> set = new HashSet<>();
    set.add(1);
    set.add(1);
    set.add(1);
    set.add(1);
    set.forEach(System.out::println);

  }
}

#출력결과

1

 

2.  순서를 보장하지 않음.

  public static void test(){
    Set<String> set = new HashSet<>();
    set.add("삼성전자");
    set.add("카카오");
    set.add("네이버");
    set.forEach(System.out::println);
  }

#출력결과

카카오
네이버
삼성전자

 

3.  Set을 List로, List를 Set으로.

  public static void test1(){
    //리스트를 Set으로
    String[] arr = {"삼성전자","카카오","네이버"};
    Set<String> set = new HashSet<>(Arrays.asList(arr));
    set.forEach(System.out::println);

    //Set을 리스트로
    List<String> list = new ArrayList<>(set);
    list.stream().forEach(System.out::println);
  }

#출력결과

카카오
네이버
삼성전자
카카오
네이버
삼성전자

 

LIST