是什么导致java.lang.arrayindexoutofboundsexception以及如何防止它?

rkkpypqq  于 2021-07-03  发布在  Java
关注(0)|答案(17)|浏览(469)

是什么 ArrayIndexOutOfBoundsException 我的意思是我该怎么摆脱它?
下面是触发异常的代码示例:

String[] names = { "tom", "bob", "harry" };
for (int i = 0; i <= names.length; i++) {
    System.out.println(names[i]);
}
2hh7jdfx

2hh7jdfx1#

对于看似神秘的arrayindexoutofboundseceptions(即显然不是由您自己的数组处理代码引起的),我见过的最常见的情况是并发使用simpledateformat。特别是在servlet或控制器中:

public class MyController {
  SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

  public void handleRequest(ServletRequest req, ServletResponse res) {
    Date date = dateFormat.parse(req.getParameter("date"));
  }
}

如果两个线程同时输入simplatedateformat.parse()方法,您可能会看到arrayindexoutofboundsexception。注意simpledateformat类javadoc的同步部分。
确保在您的代码中没有以servlet或控制器等并发方式访问simpledateformat之类的线程不安全类的地方。检查servlet和控制器的所有示例变量以查找可能的嫌疑犯。

1sbrub3j

1sbrub3j2#

您的第一个停靠港应该是合理清楚地解释它的文档:
抛出以指示已使用非法索引访问数组。索引为负数或大于或等于数组的大小。
例如:

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

至于如何避免。。。呃,别那么做。小心数组索引。
人们有时遇到的一个问题是认为数组是1索引的,例如。

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

这将丢失第一个元素(索引0),并在索引为5时引发异常。这里的有效索引包括0-4。正确的,惯用的 for 这里的声明是:

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

(当然,这是假设你需要索引。如果可以改用增强的for循环,请这样做。)

83qze16e

83qze16e3#

ArrayIndexOutOfBoundsException 意味着您正试图访问不存在或超出此数组界限的数组索引。数组索引从0开始,长度为-1。
对你来说

for(int i = 0; i<=name.length; i++) {
    System.out.print(name[i] +'\n'); // i goes from 0 to length, Not correct
}
``` `ArrayIndexOutOfBoundsException` 尝试访问不存在的name.length索引元素(数组索引以长度-1结尾)时发生。只要将<=替换为<=就可以解决这个问题。

for(int i = 0; i < name.length; i++) {
System.out.print(name[i] +'\n'); // i goes from 0 to length - 1, Correct
}

wooyq4lh

wooyq4lh4#

为了避免数组索引越界异常,应该使用增强的- for 陈述何时何地可以。
主要动机(和用例)是在迭代时,您不需要任何复杂的迭代步骤。您将无法使用增强的- for 在数组中向后移动或只迭代其他元素。
在执行此操作时,您可以保证不会耗尽要迭代的元素,而且您的[corrected]示例很容易转换。
代码如下:

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

…相当于:

String[] name = {"tom", "dick", "harry"};
for(String firstName : name) {
    System.out.println(firstName + "\n");
}
wwtsj6pe

wwtsj6pe5#

arrayindexoutofboundsexception每当出现此异常时,它意味着您试图使用超出其界限的数组索引,或者在外行术语中,您请求的索引比您初始化的要多。
为了避免这种情况,请始终确保您没有请求数组中不存在的索引,即,如果数组长度为10,则索引的范围必须介于0到9之间

ua4mk5z4

ua4mk5z46#


这就是在eclipse中抛出此类异常时的外观。红色的数字表示您试图访问的索引。所以代码如下所示:

myArray[5]

当您尝试访问该数组中不存在的索引时,会引发此错误。如果数组的长度为3,

int[] intArray = new int[3];

那么唯一有效的索引是:

intArray[0]
intArray[1]
intArray[2]

如果数组的长度为1,

int[] intArray = new int[1];

那么唯一有效的索引是:

intArray[0]

任何等于或大于数组长度的整数:都超出界限。
任何小于0的整数:超出界限;
p、 s:如果您想更好地理解数组并做一些实践练习,这里有一个视频:java数组教程

fnx2tebb

fnx2tebb7#

对于多维数组,确保访问 length 正确维度的属性。以下面的代码为例:

int [][][] a  = new int [2][3][4];

for(int i = 0; i < a.length; i++){
    for(int j = 0; j < a[i].length; j++){
        for(int k = 0; k < a[j].length; k++){
            System.out.print(a[i][j][k]);
        }
        System.out.println();
    }
    System.out.println();
}

每个维度都有不同的长度,所以微妙的缺陷是中间和内部循环使用 length 相同维度的属性(因为 a[i].length 与相同 a[j].length ).
相反,内部循环应该使用 a[i][j].length (或 a[0][0].length ,为简单起见)。

1szpjjfi

1szpjjfi8#

来自这篇优秀的文章:for循环中的arrayindexoutofboundsexception
简而言之:
在的最后一次迭代中

for (int i = 0; i <= name.length; i++) {
``` `i` 将等于 `name.length` 这是非法索引,因为数组索引是基于零的。
你的代码应该是

for (int i = 0; i < name.length; i++)
^

ruyhziif

ruyhziif9#

对于给定的数组,数组的长度是3(即name.length=3)。但当它存储从索引0开始的元素时,它的最大索引为2。
因此,您应该编写“i<name.length”而不是“i<=name.length”,以避免“arrayindexoutofboundsexception”。

os8fio9y

os8fio9y10#

这个简单的问题到此为止,但我只想强调java中的一个新特性,它将避免数组中索引的所有混淆,即使对于初学者也是如此。java-8为您抽象了迭代任务。

int[] array = new int[5];

//If you need just the items
Arrays.stream(array).forEach(item -> { println(item); });

//If you need the index as well
IntStream.range(0, array.length).forEach(index -> { println(array[index]); })

有什么好处?嗯,有一点是可读性,就像英语一样。第二,你不必担心 ArrayIndexOutOfBoundsException

jjjwad0x

jjjwad0x11#

这意味着您正试图访问无效数组的索引,因为它不在边界之间。
例如,这将初始化一个上界为4的原始整数数组。

int intArray[] = new int[5];

程序员从零开始计数。所以这个例子会抛出一个 ArrayIndexOutOfBoundsException 因为上限是4而不是5。

intArray[5];
ux6nzvsh

ux6nzvsh12#

对于长度为n的任何数组,数组元素的索引范围为0到n-1。
如果您的程序试图访问数组索引大于n-1的任何元素(或内存),那么java将抛出arrayindexoutofboundsexception
我们可以在程序中使用两种解决方案
保持计数:

for(int count = 0; count < array.length; count++) {
    System.out.println(array[count]);
}

或者像这样的循环语句

int count = 0;
while(count < array.length) {
    System.out.println(array[count]);
    count++;
}

在这种方法中,更好的方法是使用for-each循环

cmssoen2

cmssoen213#

在代码中,您访问了从索引0到字符串数组长度的元素。 name.length 给出字符串对象数组中字符串对象的数目,即3,但最多只能访问索引2 name[2] ,因为可以从索引0到 name.length - 1 你去哪了 name.length 对象数。
即使在使用 for 循环以索引0开始,应该以 name.length - 1 . 在数组a[n]中,可以从a[0]访问a[n-1]。
例如:

String[] a={"str1", "str2", "str3" ..., "strn"};

for(int i=0; i<a.length(); i++)
    System.out.println(a[i]);

就你而言:

String[] name = {"tom", "dick", "harry"};

for(int i = 0; i<=name.length; i++) {
    System.out.print(name[i] +'\n');
}
nle07wnf

nle07wnf14#

if (index < 0 || index >= array.length) {
    // Don't use this index. This is out of bounds (borders, limits, whatever).
} else {
    // Yes, you can safely use this index. The index is present in the array.
    Object element = array[index];
}

另请参见:

java教程-语言基础-数组
更新:根据你的代码片段,

for (int i = 0; i<=name.length; i++) {

索引包含数组长度。这是不允许的。你需要替换 <=< .

for (int i = 0; i < name.length; i++) {
u4dcyp6a

u4dcyp6a15#

你越来越 ArrayIndexOutOfBoundsException 由于 i<=name.length 部分。 name.length 返回字符串的长度 name ,也就是3。因此,当您尝试访问 name[3] ,它是非法的,并引发异常。
解析代码:

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

它是在java语言规范中定义的:
这个 public final 字段 length ,它包含数组的组件数。 length 可以是正或零。

相关问题