자바/자료구조

[Java] Set [HashSet]

backend dev 2022. 12. 5.

Set

HashSet은 컬렉션 인터페이스를 상속한 Set 인터페이스의 구현클래스(구현체)이다.

 

Set은 집합이라는 뜻이며 , Map과 같이 저장순서를 유지하지않는다(인덱스 없음)

또한 중복값을 허용하지 않는다 (Map처럼)

 

객체 선언

Set<Integer> set = new HashSet<>();

초기화는 List와 같은 다른 컬렉션 구현체로 바로 가능.

List<Integer> list = new ArrayList<>();
list.add(2);
list.add(2);
list.add(2);
list.add(2);

set = new HashSet<>(list);
bw.write("list to set , 중복값을 넣게되면 하나만 저장된다. :"+ set.toString());

 

값추가

Set<Integer> set = new HashSet<>();
set.add(5);
set.add(3);
set.add(4);
set.add(7);

bw.write("set 사이즈 :" + set.size()+"\n");
bw.write(set.toString() + "\n");

 

값 있는지 확인

if (set.contains(7)) {
    bw.write("해당값이 존재합니다.\n");
}

 

 

Set의 시간복잡도

Map 처럼 인덱스가 없는(== 순서가 없는) 자료구조이라서

값이 있는지 체크하는 contains()메소드의 시간복잡도는 O(1)이다.

 

 

 

 

 

 

배열을 List로, List를 배열로

List를 배열로

List<Integer> list = new ArrayList<>();
list.add(2);
list.add(3);
list.add(4);

Integer[] a = list.toArray(new Integer[0]);
bw.write(Arrays.toString(a));

콜렉션 구현체들은 .toArray 메소드를 이용하여 배열로 바꾸면 된다.

매개변수로 바꿀 오브젝트배열을 적어주고 크기를 정해주는데 0이면 알아서 크기를 맞춰주고

해당 오브젝트배열보다 큰 크기를 적어주면 남는공간에는 null을 채워준다.

 

배열을 list로

String[] a = new String[]{"a", "b", "c"};
List<String> list = new ArrayList<>(Arrays.asList(a));

bw.write(list.toString());

배열을 list로 바꿔주는 Arrays.asList() 메소드를 사용해준다.

배열을 Set으로 , Set을 배열로

배열을 Set으로 변환

Set은 Collection 인터페이스의 상속 인터페이스이므로 , 

콜렉션 구현체만 대입받아 초기화가 가능하다.

 

그래서 배열을 Set에 넣으려면 , 배열을 List로 바꿔주는 작업이 필요하다.

String[] array = new String[]{"a", "b", "c"};
Set<String> set = new HashSet<>(List.of(array));
bw.write(set.toString());

 

Set을 배열로 변환

String[] array = new String[]{"a", "b", "c"};
Set<String> set = new HashSet<>(List.of(array));

String[] array2 = set.toArray(new String[0]);

bw.write(Arrays.toString(array2));

Set을 배열로 변환하려면   

.toArray() 메소드를 사용해야한다. 해당 메소드의 매개변수에는 어떤 배열로 바꿀것인지를 적어줘야한다.

int와 같은 primitive 타입은 안되고 Wrapper타입(String,Integer 등)만 된다.

파라미터 : new Object[]

뒤에 크기를 적는 부분에는 0을 적어주면 해당 Set의 크기만큼 알아서 생성해준다.!

 

 

List를 Set으로 Set을 List로

List<Integer> list = new ArrayList<>();
list.add(2);
list.add(3);
list.add(4);

Set<Integer> set = new HashSet<>(list);

bw.write(set.toString());

ArrayList는 Collection의 구현체이므로 Set에 그냥 할당해서 Set을 초기화 가능하다.

 

Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);

List<Integer> list = new ArrayList<>(set);
bw.write(list.toString());

Set도 콜렉션 구현체이므로 list를 이용하여 초기화 가능.

 

 

 

 

 

 

 

 

 

[Java] 배열을 List로, List를 배열로 변환하기

배열을 List로 Arrays.asList() new ArrayList(Arrays.asList()) Collectors.toList() ArrayList를 배열로 toArray() - java.util.List 배열을 List로 1. Arrays.asList() 코드 import java.util.Arrays; import java.util.List; public class ArrayConversion

hianna.tistory.com

 

Java - Set를 List로, List를 Set로 변환하는 방법

Set를 List로, List를 Set로 변환, List를 Array로, Array를 List로 변환, Set를 Array로, Array를 Set로 변환하는 방법을 소개합니다. 또한 구글 자바 라이브러리 Guava를 이용한 예제도 소개합니다.

codechacha.com

 

'자바 > 자료구조' 카테고리의 다른 글

[Java] 우선순위 큐 (Priority Queue)  (0) 2022.12.24
[Java] Heap, 힙 , 트리, 이진트리, 완전 이진트리  (0) 2022.12.24
[Java] Stack, 스택  (0) 2022.12.20
[Java] HashMap  (1) 2022.12.04
[Java] ArrayList, LinkedList  (0) 2022.12.03

댓글