본문 바로가기

시즌1/Java Tips

[Java Tips] ArrayList를 array로 변환하는 방법


ArrayList를 쓰다 보면 가끔 array로 변환해야 하는 경우가 발생합니다.
여러 가지 방법이 있겠지만, 다음과 같이, 두 가지 방법을 주로 쓰게 됩니다.

  1. array를 생성한 다음, for 문을 통해 assign 하는 방법
  2. ArrayList.toArray() 또는 ArrayList.toArray(T[] a)를 이용하는 방법

1번 보다는 2번 방법이 성능 면이나 코드 가독성 면에서 추천합니다.

샘플 1 : ArrayList.toArray()를 이용하는 법

import java.util.ArrayList;

public class ArrayListToArray {

	public static void main(String[] args) {

		// Array List 생성
		ArrayList al = new ArrayList();

		// Item Add
		al.add(new Integer(1));
		al.add(new Integer(2));
		al.add(new Integer(3));
		al.add(new Integer(4));
		al.add(new Integer(5));

		System.out.println("contents of al : " + al);
		Object[] ia = al.toArray(); // ArrayList를 array로 변환
		int sum = 0;

		// sum the array
		for (int i = 0; i < ia.length; i++)
			sum += ((Integer) ia[i]).intValue();

		System.out.println("Sum is :" + sum);

	}

}

위와 같이, ArrayList.toArray() Method의 경우, Object array를 리턴합니다.
이럴 경우, 적절히 타입 캐스팅을 해서 사용을 해야 하는 번거로움이 있습니다.

반면, 샘플 2를 보시면,

샘플 2 : ArrayList.toArray(T[] t)를 이용하는 방법

import java.util.ArrayList;

public class ArrayListToArray {

	public static void main(String[] args) {

		// Array List 생성
		ArrayList al = new ArrayList();

		// Item Add
		al.add(new Integer(1));
		al.add(new Integer(2));
		al.add(new Integer(3));
		al.add(new Integer(4));
		al.add(new Integer(5));

		System.out.println("contents of al : " + al);
		Integer[] ia = al.toArray(new Integer[] { 0 }); // ArrayList를 array로 변환
		int sum = 0;

		// sum the array
		for (int i = 0; i < ia.length; i++)
			sum +=  ia[i].intValue();

		System.out.println("Sum is :" + sum);

	}

}

위와 같이, 리턴될 array의 타입을 지정해 줄 수 있습니다.
ArrayList에 동일한 class의 object들이 들어 있는 경우, 번거롭게, 타입 캐스팅을 할 필요가 없습니다.

정리하자면, ArrayList에 여러 가지 class의 object가 있는 경우는, ArrayList.toArray()를 사용하는 것이 편하고, 동일한 class의 object가 있는 경우는 ArrayList.toArray(T[] t)를 사용하시는 것이 편합니다.