📗 Docs

[Java] int[] 배열을 Integer[]배열로 / List 에서 Array로, Array에서 List로

파일과 미디어
date
Apr 20, 2023
slug
Array-List
author
status
Public
tags
Java
Blog
summary
Java Array / ArrayList 활용
type
Post
thumbnail
category
📗 Docs
updatedAt
Apr 24, 2023 06:33 PM
프로그래밍을 하다보면 데이터 자료구조를 변환해야할 때가 있다.
특히 int[] ↔ ArrayList간의 변환시 ArrayList는 기본적으로 Object 타입을 반환하기 때문에 자료형 일치를 위해 두번에 걸쳐 변환해주어야한다.
 

int[] ↔ Integer[]

int[] a = new int[] {1,2,3,4};

//int[] - > Integer[]
Integer [] conver = Arrays.stream(a).boxed().toArray(Integer[]::new);

//Integer[] -> int[]
a = Arrays.stream(conver).mapToInt(Integer::intValue).toArray();
[Java] Stream - Array에서 min, max 구하기 ← stream중 boxed를 하는 이유 설명
 

List → Array(배열)

//1.for문
ArrayList<String> arrayList = new ArrayList<>();

arrayList.add("Test1");
arrayList.add("Test2");
arrayList.add("Test3");

String[] array = new String[arrayList.size()];
int idx = 0;
for(String temp : arrayList){
	array[idx++] = temp;
}

//2.List 메서드 사용

ArrayList<String> arrayList = new ArrayList<>();

arrayList.add("Test1");
arrayList.add("Test2");
arrayList.add("Test3");

String[] array = arrayList.toArray(new String[arrayList.size()]);
 

Array → List

//1.for문
String[] array = new String[3];



array[0] = "Test1";
array[1] = "Test2";
array[2] = "Test3";

ArrayList<String> arrayList = new ArrayList<>();

for(String temp : array){
  arrayList.add(temp);
}

//2.Arrays메서드 사용
String[] array = new String[3];

array[0] = "Test1";
array[1] = "Test2";
array[2] = "Test3";

ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(array));