Java
java.lang.IndexOutOfBoundsException
Darane
2020. 5. 4. 10:30
리스트나 배열을 사용하다 보면 종종 IndexOutOfBoundsException이 발생하는 경우가 있다. 리스트나 배열의 원소(Element)에 접근하다가 Exception이 발생하는데 아래의 예제를 통해 확인해 보자.
1. 예제
반복문
ArrayList<String> colors = new ArrayList<>();
for (int i = 0; i <= colors.size(); i++) {
colors.get(i); //에러발생
}
Exception
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:373)
at java.base/java.util.ArrayList.get(ArrayList.java:426)
at test/test.Manager.main(Manager.java:21)
리스트 값 얻어오기
ArrayList<String> colors = new ArrayList<>();
colors.add("Blue");
colors.add("Red");
colors.get(2); //에러발생
Exception
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:373)
at java.base/java.util.ArrayList.get(ArrayList.java:426)
at test/test.Manager.main(Manager.java:22)
IndexOutOfBoundsException 문서의 설명을 보면 다음과 같다.
"Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range."
위의 설명과 같이 배열의 범위를 넘어서는 인덱스에 접근하게 되면 IndexOutOfBoundsException이 발생한다.
2. 해결방법
인덱스를 통한 리스트 접근할 때 사이즈를 미리 확인해준다.
if (colors.size() != 2) {
colors.get(2);
}
for-each를 사용한다.
리스트를 순회할 때 인덱스를 통한 접근을 사용하지 않으므로 인덱스 직접 접근 시 실수로 발생하는 에러를 줄일 수 있다.
for (String color : colors) {
System.out.println(color);
}
반응형