归咎于寂寞的夏天.|

Phantasia1116

园龄:1年7个月粉丝:0关注:7

2024-03-21 12:08阅读: 33评论: 0推荐: 0

ArrayIndexOutOfBoundException and NegativeArraySizeException in Java

ArrayIndexOutOfBoundException

ArrayIndexOutOfBoundsException occurs when we access an array, or a Collection, that is backed by an array with an invalid index. This means that the index is either less than zero or greater than or equal to the size of the array.

  • 也就是说,使用 index 索引数组的时候可能出现了负数或者是大于数组长度的数

可能出错的情况

越界访问数组

Accessing the array elements out of these bounds would throw an ArrayIndexOutOfBoundsException:

int[] numbers = new int[] {1, 2, 3, 4, 5};
int lastNumber = numbers[5];

Here, the size of the array is 5, which means the index will range from 0 to 4.
In this case, accessing the 5th index results in an ArrayIndexOutOfBoundsException:

Here, the size of the array is 5, which means the index will range from 0 to 4.
In this case, accessing the 5th index results in an _ArrayIndexOutOfBoundsException_:
访问由 Arrays.asList() 返回的 List

If we try to access the elements of the List returned by Arrays.asList() beyond this range, we would get an ArrayIndexOutOfBoundsException:

List<Integer> numbersList = Arrays.asList(1, 2, 3, 4, 5);
int lastNumber = numbersList.get(5);

Here again, we are trying to get the last element of the List. The position of the last element is 5, but its index is 4 (size – 1). Hence, we get ArrayIndexOutOfBoundsException as below:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4351)
at ...
循环遍历数组

Sometimes, while iterating over an array in a for loop, we might put a wrong termination expression.

Instead of terminating the index at one less than the length of the array, we might end up iterating until its length:

int sum = 0;
for (int i = 0; i <= numbers.length; i++) {
sum += numbers[i];
}

In the above termination expression, the loop variable i is being compared as less than or equal to the length of our existing array numbers. So, in the last iteration, the value of i will become 5.

Since index 5 is beyond the range of numbers, it will again lead to ArrayIndexOutOfBoundsException:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at com.baeldung.concatenate.IndexOutOfBoundExceptionExamples.main(IndexOutOfBoundExceptionExamples.java:22)

Avoid This Exception

  • Remembering the index
  • Correctly Using the Operators in Loops
  • Using Enhanced for Loops (using iterator)

NegativeArraySizeException

什么导致了NegativeArraySizeException in Java

The NegativeArraySizeException occurs when an attempt is made to assign a negative size to an array. Here's an example:

public class NegativeArraySizeExceptionExample {
public static void main(String[] args) {
int[] array = new int[-5];
System.out.println("Array length: " + array.length);
}
}

Running the above code throws the following exception:

Exception in thread "main" java.lang.NegativeArraySizeException: -5
at NegativeArraySizeExceptionExample.main(NegativeArraySizeExceptionExample.java:3)

怎么解决 NegativeArraySizeException in Java

The NegativeArraySizeException can be handled in code using the following steps:

  • Surround the piece of code that can throw an NegativeArraySizeException in a try-catch block.
  • Catch the NegativeArraySizeException in the catch clause.
  • Take further action as necessary for handling the exception and making sure the program execution does not stop.

Here's an example of how to handle it in code:

public class NegativeArraySizeExceptionExample {
public static void main(String[] args) {
try {
int[] array = new int[-5];
} catch (NegativeArraySizeException nase) {
nase.printStackTrace();
//handle the exception
}
System.out.println("Continuing execution...");
}
}

In the above example, the lines that throw the NegativeArraySizeException are placed within a try-catch block. The NegativeArraySizeException is caught in the catch clause and its stack trace is printed to the console. Any code that comes after the try-catch block continues its execution normally.

Running the above code produces the following output:

java.lang.NegativeArraySizeException: -5
at NegativeArraySizeExceptionExample.main(NegativeArraySizeExceptionExample.java:4)
Continuing execution...

怎么避免 NegativeArraySizeException in Java

Since the NegativeArraySizeException occurs when an array is created with a negative size, assigning a positive size to the array can help avoid the exception. Applying this to the earlier example helps fix the issue:

public class NegativeArraySizeExceptionExample {
public static void main(String[] args) {
int[] array = new int[5];
System.out.println("Array length: " + array.length);
}
}

The array is initialized with a size of 5, which is a positive number. Running the above code produces the correct output as expected:

Array length: 5

reference:

本文作者:Phantasia1116

本文链接:https://www.cnblogs.com/Phantasia/p/18087086

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Phantasia1116  阅读(33)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起