제리의 배움 기록

[Java] ArrayList의 toArray() 본문

자바

[Java] ArrayList의 toArray()

제리92 2021. 11. 12. 10:29

ArrayList는 자바로 개발을 하면서 가장 많이 쓰는 리스트의 구현 클래스 중 하나입니다.

ArrayList 타입의 String 리스트를 배열로 변환하려 할때는 아래와 같이 사용합니다.

ArrayList<String> strs=new ArrayList<>(); 
strs.toArray(new String[0]);

이때 strs.toArray(new String[0]); 은 어떻게 동작하는 것일까요?

ArrayList 살펴보기

ArrayList는 toArray를 다음과 같이 구현하였습니다.

  public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

1.첫번째 if 분기에서는 메서드 파라미터 a로 넘겨받은 배열의 길이가 해당 ArrayList 객체의 size 보다 작은 경우 (a.length < size) size만큼 배열을 생성하고 ArrayList의 데이터 복사 후 리턴합니다.

2.a 배열의 길이가 해당 ArrayList 객체의 size 보다 크거나 같은 경우 (if 분기 이후. a.length >= size) 배열 a에 ArrayList 데이터를 복사합니다.

3.a 배열의 길이가 > ArrayList 객체 size 경우(a.length > size) a[size] = null을 할당합니다.

참조타입 배열은 초기화시 null로 초기화되므로 해당 로직이 필요없을 수 있지만, 초기화한 배열이 아닌 기존에 값이 들어있는 재사용하고자 전달한 경우엔 필요한 로직입니다.

그래서 ArrayList를 배열로 변경할 경우 길이 0의 배열 strs.toArray(new String[0]); 을 넘겨주면 ArrayList 길이만큼 배열을 자동으로 생성하고 데이터를 복사하게 됩니다.

코드로 확인하기

public class ArrayListTest {

    private List<String> testList;

    @BeforeEach
    void setup(){
        testList =new ArrayList<>();
        testList.add("hi");
        testList.add("welcome");
        testList.add("glad");
    }

    @Test
    void toArray_size_같은_배열길이(){
        int arrLen = testList.size();
        String[] convetedArr = testList.toArray(new String[arrLen]);
        assertThat(convetedArr.length).isEqualTo(arrLen);
        for(int i=0; i<arrLen; i++){
            assertThat(testList.get(i)).isEqualTo(convetedArr[i]);
        }
    }

    @Test
    void toArray_size_보다_큰_배열길이(){
        int arrLen = testList.size();
        String[] convetedArr = testList.toArray(new String[arrLen+1]);
        assertThat(convetedArr.length).isEqualTo(arrLen+1);
        assertThat(convetedArr[arrLen]).isNull();
    }

    @Test
    void toArray_size_보다_큰_배열길이_값이들어있는경우(){
        int arrLen = testList.size();
        String[] existArr= {"a","b","c","d","e","f"};
        String[] convetedArr = testList.toArray(existArr);
        assertThat(convetedArr.length).isEqualTo(existArr.length);
        assertThat(convetedArr[arrLen]).isNull();   // size 위치 index에만 null 할당
        for(int i=arrLen+1; i<existArr.length; i++){
            assertThat(convetedArr[i]).isEqualTo(existArr[i]);
        }
    }

    @Test
    void toArray_size_보다_작은_배열길이(){
        int arrLen = testList.size();
        String[] convetedArr = testList.toArray(new String[0]);
        assertThat(convetedArr.length).isEqualTo(arrLen);
    }
}

더 많은 자바 학습테스트 보기

Comments