什么原因导致java.lang.ArrayIndexOutOfBoundsException,我如何prevent呢? [英] What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

查看:159
本文介绍了什么原因导致java.lang.ArrayIndexOutOfBoundsException,我如何prevent呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是什么 ArrayIndexOutOfBoundsException异常的意思是,我如何摆脱它?

下面是触发异常的code样品:<​​/ P>

 的String [] NAME = {汤姆,迪克,哈利};
的for(int i = 0; I&LT; = name.length;我++){
  System.out.print(名称[I] +的'\\ n');
}


解决方案

您的第一个停靠港应该是<一个href=\"http://download.oracle.com/javase/6/docs/api/java/lang/ArrayIndexOutOfBoundsException.html\">documentation这也解释了其合理清楚的:


  

抛出,表明数组已用非法索引访问。该指数是负或大于或等于所述阵列的大小。


因此​​,例如:

  INT []数组=新INT [5];
INT热潮=阵列[10]; //抛出异常

至于如何避免它......嗯,不这样做。小心你的数组索引。

有一个问题人们有时会碰到被认为阵列1索引,例如

  INT []数组=新INT [5];
// ...这里填充阵列...
对于(INT指数= 1;指数&LT; = array.length;指数++)
{
    的System.out.println(数组[指数]);
}

这将错过的第一个元素(索引0),并且当索引是5。这里的有效指标是0-4包容抛出异常。这里正确的,地道的语句应该是:

 为(INT指数= 0;指数 -  LT; array.length;指数++)

(这是假设你的需求的指标,当然,如果你能使用增强的for循环,这样做的。)

What does ArrayIndexOutOfBoundsException mean and how do I get rid of it?

Here is a code sample that triggers the exception:

String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<=name.length; i++) {
  System.out.print(name[i] +'\n');
}

解决方案

Your first port of call should be the documentation which explains it reasonably clearly:

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

So for example:

int[] array = new int[5];
int boom = array[10]; // Throws the exception

As for how to avoid it... um, don't do that. Be careful with your array indexes.

One problem people sometimes run into is thinking that arrays are 1-indexed, e.g.

int[] array = new int[5];
// ... populate the array here ...
for (int index = 1; index <= array.length; index++)
{
    System.out.println(array[index]);
}

That will miss out the first element (index 0) and throw an exception when index is 5. The valid indexes here are 0-4 inclusive. The correct, idiomatic for statement here would be:

for (int index = 0; index < array.length; index++)

(That's assuming you need the index, of course. If you can use the enhanced for loop instead, do so.)

这篇关于什么原因导致java.lang.ArrayIndexOutOfBoundsException,我如何prevent呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆