늘 겸손하게

Java ArrayList 주의점 - IndexOutOfBoundsException 본문

Programming/Java

Java ArrayList 주의점 - IndexOutOfBoundsException

besforyou999 2022. 2. 20. 16:00

문제 : 계속 IndexOutOfBoundsException이 뜬다.

 

분명이 initialCapacity를 N+1로 하고 N 이하 인덱스로 ArrayList에 접근하려는데 indexOutOfBoundsException 오류가 발생하였다.

 

1
tree = new ArrayList<>(N+1);
cs

 

1
tree.set(rt - 'A', node);
cs

rt - 'A' 값은 0 이상 N 이하

 

 

 

왜 인지 찾아보니 initialCapacity는 말 그대로 초기 최대 용량을 말하는것이지 ArrayList의 길이가 N+1로 초기화되는것이 아니였다.

 

 

해결책 : 원하는 길이만큼 초기화 시켜준다.

 

간단히 인덱스 0부터 N까지 초기화 해주니 오류가 사라졌다.

 

1
2
3
for (int i = 0 ; i <= N ; i++) {
    tree.add(new Node('A','A'));
}
cs