java.lang.ArrayIndex_了解Java中的java.lang.ArrayIndexOutOfBoundsException异常 - Break易站

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语句的块内部小心,因为如果我们不适当地处理异常,我们可能会隐藏它,从而在您的应用程序中创建一个错误。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值