Solution to Java data index exception (IndexOutOfBoundsException)
Introduction:
In Java programming, when accessing a non-existent array element or collection When the index exceeds the range, an IndexOutOfBoundsException exception will be thrown. This is a common mistake that many beginners often encounter. This article will introduce how to avoid and solve IndexOutOfBoundsException exception with some simple solutions.
Sample Code 1:
int[] array = new int[5]; int index = 5; array[index] = 10; // 此处抛出IndexOutOfBoundsException异常
In the above code, we have created an integer array of length 5, but while trying to assign the value to the element with index 5 , an IndexOutOfBoundsException exception will be thrown. This is because the index of an array is calculated starting from 0, so the valid index range of the array should be 0 to 4. Solving this problem simply requires calculating the index correctly.
Sample code 2:
int[] array = new int[5]; int index = 4; array[index] = 10; // 正确的索引赋值
Sample Code 3:
List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); int index = 2; int value = list.get(index); // 此处抛出IndexOutOfBoundsException异常
In the above code, we created an empty ArrayList and tried to get the element value with index 2, but since there are only two elements, So accessing the element with index 2 will throw an IndexOutOfBoundsException exception. To solve this problem, you can determine the size or length of the collection before accessing it.
Sample code 4:
List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); int index = 1; if (index < list.size()) { int value = list.get(index); // 正确的访问 }
Method 1: for loop control:
for (int i = 0; i < array.length; i++) { // 访问数组元素 }
When using a for loop, control the loop by using the length of the array or collection times to ensure that the range of the index is not exceeded.
Method 2: foreach loop control:
for (int value : array) { // 访问数组元素 }
When using a foreach loop, you do not need to care about the range of the index, because the underlying layer has already made relevant judgments, so there will be no IndexOutOfBoundsException exception.
To sum up, through correct index calculation, non-null judgment and loop control, we can avoid and solve the IndexOutOfBoundsException exception in Java. These simple solutions can improve the robustness and readability of our code, and can also better help us locate and fix errors. For Java program developers, mastering these skills is very important to improve the quality and efficiency of the code.
Reference materials:
The above is the detailed content of Solution to Java data index exception (IndexOutOfBoundsException). For more information, please follow other related articles on the PHP Chinese website!