본문 바로가기

Backend/Trouble Shooting

[Java] Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 오류 해결

class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = {};
        for(int i = 0; i < num_list.length; i++)
            answer[i] = num_list[num_list.length-1-i];
        return answer;
    }
}

다음과 같이 작성하면 ArrayIndexOutOfBoundsException 오류가 발생한다.

answer 배열의 크기를 지정하지 않아서 그렇다.

 

class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = new int[num_list.length];
        for(int i = 0; i < num_list.length; i++)
            answer[i] = num_list[num_list.length-1-i];
        return answer;
    }
}

이렇게 배열의 크기를 지정해서 해결할 수 있다.