본문 바로가기
JAVA/기본

자료구조 초기화, List-Array 변환

by 히포파타마스 2022. 7. 15.

자료구조 초기화, List-Array 변환

Array와 Map 그리고, Collection의 구현체인 List, Set의 초기화 방법을 알아본다.

그리고 필요할 때 맨날 까먹는 List와 Array간의 변환도 살펴본다.

 

 

1. 초기화

자료구조로 만들 데이터를 알고있을 때 되도록 한번에 각 자료구조를 초기화 하는 방법을 알아본다.

 

 

■ Array

[Array 초기화]

String[] string1 = new String[]{"hello", "hi"};

String[] string2 = {"hello", "hi"};

 

 

 

■ List

List.of()를 사용해서 초기화한다.

 

[List 초기화]

List<String> stringList1 = List.of("hello", "hi");   //[1]

List<String> stringList2 = new ArrayList<>(List.of("hello", "hi"));

● [1] : List.of()를 사용해서 만들어진 List는 변경 불가능한 상태가 된다.

             변경 가능한 List를 생성하고 싶다면 아래에서 ArrayList를 생성하기 위해 List.of()를 사용한것과 같이 List.of()를 직접사용하지

             않으면 된다.

 

 

 

■ Set

Set.of()를 사용해서 초기화 한다.

 

[Set 초기화]

Set<String> set1 = Set.of("hello", "hi");   //변경 불가

Set<String> set2 = new HashSet<>(Set.of("hello", "hi"));

List.of()와 같이 Set.of()를 사용해서 만들어진 Set은 변경 불가능한 상태가 된다.

 

 

 

■ Map

Map은 Collection은 아니지만 Collection에서 제공되는 기능들과 유사한 기능들이 제공된다.

 

[Map 초기화]

HashMap<String, String> hashMap = new HashMap<>() {   //[1]
    {
        put("1", "hello");
        put("2", "hi");
    }
};

Map<String, String> map = Map.of("1", "hello", "2", "hi");   //[1]

● [1] : 대부분의 Collection에서 add()를 사용해서 초기화 할 수 있는것 처럼 Map도 put()을 이용해서 초기화 할 수 있다.

● [2] : List.of(), Set.of()와 유사한 Map.of()가 제공되어 Key, Value를 번갈아 가며 입력하는 것으로 Map을 초기화 할 수 있다.

             Map.of()를 사용해 생성된 Map은 변경 불가이며, Key와 Value값도 최대 10개 까지 밖에 받을 수 없다.

 

※ Collection은 add()를 사용해서 초기화 할 수 있다.

 

[add를 사용한 초기화]

ArrayList<String> strings1 = new ArrayList<>() {
    {
        add("hello");
        add("hi");
    }
};

HashSet<String> strings2 = new HashSet<>() {
    {
        add("hello");
        add("hi");
    }
};

 

 

 

 

2. List-Array 변환

■ List -> Array

List에 toArray() 메서드를 사용해서 Array로 변환한다.

 

[List -> Array]

List<String> stringList = new ArrayList<>(List.of("hello", "hi"));
String[] strings = stringList.toArray(new String[0]);

List<Integer> integerList = new ArrayList<>(List.of(1, 2));
Integer[] integers = integerList.toArray(new Integer[0]);
//int[] integers = integerList.toArray(new int[0]);

● toArray()의 매개변수로는 변환할 배열의 타입의 인스턴스를 넣어준다.

    매개변수의 길이는 List의 길이 이하가 되야하며 List의 길이보다 크면 비어있는 배열이 반환된다.

● toArray()를 사용할 경우 기본형 타입의 배열으로는 바로 변경할 수 없다.

 

 

 

■ Array -> List

List.of()를 사용해서 List로 변환한다.

 

[Array -> List]

String[] strings = {"hello", "hi"};
List<String> stringList = List.of(strings);

int[] ints = {1, 2, 3};
//List<Integer> integerList = List.of(ints);

● List.of()를 사용할 경우 기본형 타입의 배열을 List로 바로 변환할 수 없다.

 

 

□ 기본형 배열으로 변환

[기본형 배열으로 변환]

int[] ints = {1, 2, 3};
List<Integer> integerList = Arrays.stream(ints)
        .boxed()
        .collect(Collectors.toList());

● 반복문으로 기본형 배열의 원소들을 boxing한 값들을 새로운 리스트에 넣어준다.

● 반복문 대신  stream을 사용할 수 있다.

 

 

□ Arrays.asList()

List.of()는 Java 9 부터 지원되기 때문에 그 이전 버전의 Java에서는 사용할 수 없다.

때문에 Java 9 이전 버전에서는 Arrays.asList()를 사용해서 Array를 List로 변환해야 한다.

 

[Arrays.asList()]

String[] strings = {"hello", "hi"};
List<String> stringList = Arrays.asList(strings);

strings[0] = "test";
System.out.println(stringList.get(0));  //test 출력, 배열과 원소값을 공유한다.

● List.of()와 같이 Arrays.asList()에 배열을 넣어 해당 배열의 원소를 갖는 List를 생성할 수 있다.

● List.of()와 달리 Arrays.asList()로 생성된 List는 변경 가능하다.

● Arrays.asList()는 배열을 "참조" 하여 List를 생성하기 때문에 원소값을 공유한다.

    때문에 근본적으로 Array의 성질을 갖기 때문에 add나 remove등 크기가 변하게 되는 함수를 사용할 수 없다.

 

 

 

'JAVA > 기본' 카테고리의 다른 글

Comparator 구현  (0) 2022.08.11
스트림(Stream)  (0) 2021.12.08
Optional  (0) 2021.12.03
람다(Lambda)  (0) 2021.11.28
예외 처리(exception handling)  (0) 2021.08.02

댓글