Java 数组
java.lang.ArrayIndexOutOfBoundsException
Java支持创建和操作数组,作为数据结构。数组的索引是一个整数值,其值在区间[0,n-1]中,其中n是数组的大小。如果请求负数或大于或等于数组大小的索引,则JAVA将抛出ArrayIndexOutOfBounds异常。这不像C / C ++那样没有绑定检查的索引。
ArrayIndexOutOfBoundsException是仅在运行时引发的运行时异常。Java编译器在编译程序期间不检查这个错误。
// A Common cause index out of bound
public class NewClass2
{
public static void main(String[] args)
{
int ar[] = {1, 2, 3, 4, 5};
for (int i=0; i<=ar.length; i++)
System.out.println(ar[i]);
}
}
运行时错误会引发异常:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at NewClass2.main(NewClass2.java:5)
输出:
1
2
3
4
5
这里如果你仔细看,数组的大小是5.因此,当使用for循环访问它的元素时,索引的最大值可以是4,但是在我们的程序中它将一直持续到5,因此是例外。
让我们看看另一个使用数组列表的例子:
// One more example with index out of bound
import java.util.ArrayList;
public class NewClass2
{
public static void main(String[] args)
{
ArrayList lis = new ArrayList<>();
lis.add("My");
lis.add("Name");
System.out.println(lis.get(2));
}
}
这里的运行时错误比以前的时间提供了更多信息 -
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at NewClass2.main(NewClass2.java:7)
让我们通过一些细节来了解它 -
这里的索引定义了我们试图访问的索引。
大小为我们提供了列表大小的信息。
由于大小为2,我们可以访问的最后一个索引是(2-1)= 1,因此是例外
访问数组的正确方法是:
for(int i = 0; i
{
}
处理例外情况:
使用for-each循环:这会在访问数组元素时自动处理索引。例-
for(int m:ar){
}
使用Try-Catch: 考虑将你的代码放在try-catch语句中并相应地处理异常。如前所述,Java不会让您访问无效索引,并且肯定会抛出ArrayIndexOutOfBoundsException。但是,我们应该在catch语句的块内部小心,因为如果我们不适当地处理异常,我们可能会隐藏它,从而在您的应用程序中创建一个错误。