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

发布于 2024-10-30 16:49:47 字数 224 浏览 7 评论 0 原文

ArrayIndexOutOfBoundsException 是什么意思以及如何摆脱它?

下面是触发异常的代码示例:

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

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

Here is a code sample that triggers the exception:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(25

俏︾媚 2024-11-06 16:49:47

您的第一个调用端口应该是文档这解释得相当清楚:

抛出此异常表示已使用非法索引访问了数组。索引可以为负数,也可以大于或等于数组的大小。

例如:

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(包括 0-4)。这里正确、惯用的 for 语句是:(

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

当然,这是假设您需要索引。如果您可以使用增强的 for 循环,那就这样做。)

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.)

坏尐絯℡ 2024-11-06 16:49:47

基本上:

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];
}

在您的具体情况下,

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

索引包含数组的长度。这是越界的。您需要将 <= 替换为 <

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

另请参阅:

Basically:

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];
}

In your specific case,

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

the index is inclusive the array's length. This is out of bounds. You need to replace <= by <.

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

See also:

亣腦蒛氧 2024-11-06 16:49:47

简而言之:

i的最后一次迭代中,

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

将等于 name.length,这是一个非法索引,因为数组索引是从零开始的。

你的代码应该是这样的

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

To put it briefly:

In the last iteration of

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

i will equal name.length which is an illegal index, since array indices are zero-based.

Your code should read

for (int i = 0; i < name.length; i++) 
                  ^
残龙傲雪 2024-11-06 16:49:47

这意味着您正在尝试访问无效的数组索引,因为它不在边界之间。

例如,这将初始化一个上限为 4 的原始整数数组。

int intArray[] = new int[5];

程序员从零开始计数。例如,由于上限是 4 而不是 5,因此会抛出 ArrayIndexOutOfBoundsException。

intArray[5];

It means that you are trying to access an index of an array which is not valid as it is not in between the bounds.

For example this would initialize a primitive integer array with the upper bound 4.

int intArray[] = new int[5];

Programmers count from zero. So this for example would throw an ArrayIndexOutOfBoundsException as the upper bound is 4 and not 5.

intArray[5];
平生欢 2024-11-06 16:49:47

什么原因导致ArrayIndexOutOfBoundsException

如果您将变量视为可以在其中放置值的“盒子”,那么数组就是一系列彼此相邻放置的盒子,其中盒子的数量是有限且显式的整数。

创建一个像这样的数组:

final int[] myArray = new int[5]

创建一行 5 个框,每个框保存一个 int。每个盒子都有一个索引,即一系列盒子中的位置。该索引从 0 开始,到 N-1 结束,其中 N 是数组的大小(框的数量)。

要从这一系列框中检索其中一个值,您可以通过其索引引用它,如下所示:

myArray[3]

这将为您提供该系列中第四个框的值(因为第一个框的索引为 0)。

ArrayIndexOutOfBoundsException 是由于尝试通过传递高于最后一个“框”索引或负数的索引来检索不存在的“框”而引起的。

以我的运行示例为例,这些代码片段会产生这样的异常:

myArray[5] //tries to retrieve the 6th "box" when there is only 5
myArray[-1] //just makes no sense
myArray[1337] //way to high

如何避免 ArrayIndexOutOfBoundsException

为了防止 ArrayIndexOutOfBoundsException,有一些关键点要考虑:

循环

当循环数组时,请始终确保要检索的索引严格小于数组的长度(框的数量)。例如:

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

注意 <,切勿在其中混合 =

您可能想要做这样的事情:

for (int i = 1; i <= myArray.length; i++) {
    final int someint = myArray[i - 1]

只是不要这样做。坚持上面的方法(如果你需要使用索引),它会帮你省去很多麻烦。

如果可能,请使用 foreach:

for (int value : myArray) {

这样您就根本不必考虑索引。

循环时,无论您做什么,都不要更改循环迭代器的值(此处:i)。唯一应该改变值的地方是保持循环继续。否则更改它只会冒出现异常的风险,并且在大多数情况下没有必要。

检索/更新

当检索数组的任意元素时,请始终检查它是否是针对数组长度的有效索引:

public Integer getArrayElement(final int index) {
    if (index < 0 || index >= myArray.length) {
        return null; //although I would much prefer an actual exception being thrown when this happens.
    }
    return myArray[index];
}

What causes ArrayIndexOutOfBoundsException?

If you think of a variable as a "box" where you can place a value, then an array is a series of boxes placed next to each other, where the number of boxes is a finite and explicit integer.

Creating an array like this:

final int[] myArray = new int[5]

creates a row of 5 boxes, each holding an int. Each of the boxes has an index, a position in the series of boxes. This index starts at 0 and ends at N-1, where N is the size of the array (the number of boxes).

To retrieve one of the values from this series of boxes, you can refer to it through its index, like this:

myArray[3]

Which will give you the value of the 4th box in the series (since the first box has an index of 0).

An ArrayIndexOutOfBoundsException is caused by trying to retrieve a "box" that does not exist, by passing an index that is higher than the index of the last "box", or negative.

With my running example, these code snippets would produce such an exception:

myArray[5] //tries to retrieve the 6th "box" when there is only 5
myArray[-1] //just makes no sense
myArray[1337] //way to high

How to avoid ArrayIndexOutOfBoundsException

In order to prevent ArrayIndexOutOfBoundsException, there are some key points to consider:

Looping

When looping through an array, always make sure that the index you are retrieving is strictly smaller than the length of the array (the number of boxes). For instance:

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

Notice the <, never mix a = in there..

You might want to be tempted to do something like this:

for (int i = 1; i <= myArray.length; i++) {
    final int someint = myArray[i - 1]

Just don't. Stick to the one above (if you need to use the index) and it will save you a lot of pain.

Where possible, use foreach:

for (int value : myArray) {

This way you won't have to think about indexes at all.

When looping, whatever you do, NEVER change the value of the loop iterator (here: i). The only place this should change value is to keep the loop going. Changing it otherwise is just risking an exception, and is in most cases not necessary.

Retrieval/update

When retrieving an arbitrary element of the array, always check that it is a valid index against the length of the array:

public Integer getArrayElement(final int index) {
    if (index < 0 || index >= myArray.length) {
        return null; //although I would much prefer an actual exception being thrown when this happens.
    }
    return myArray[index];
}
乱了心跳 2024-11-06 16:49:47

为了避免数组索引越界异常,应该使用 增强型-for 声明何时何地都可以。

主要动机(和用例)是当您进行迭代并且不需要任何复杂的迭代步骤时。您无法能够使用增强的-for在数组中向后移动或仅迭代每个其他元素。

执行此操作时,保证不会用完要迭代的元素,并且您的[更正]示例很容易转换。

下面的代码:

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");
}

To avoid an array index out-of-bounds exception, one should use the enhanced-for statement where and when they can.

The primary motivation (and use case) is when you are iterating and you do not require any complicated iteration steps. You would not be able to use an enhanced-for to move backwards in an array or only iterate on every other element.

You're guaranteed not to run out of elements to iterate over when doing this, and your [corrected] example is easily converted over.

The code below:

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

...is equivalent to this:

String[] name = {"tom", "dick", "harry"};
for(String firstName : name) {
    System.out.println(firstName + "\n");
}
萝莉病 2024-11-06 16:49:47

在您的代码中,您已访问从索引 0 到字符串数组长度的元素。 name.length 给出字符串对象数组中字符串对象的数量,即 3,但您最多只能访问索引 2 name[2]
因为可以从索引 0 到 name.length - 1 访问该数组,您可以在其中获取 name.length 对象数量。

即使在使用 for 循环时,您也以索引零开始,并且应该以 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');
}

In your code you have accessed the elements from index 0 to the length of the string array. name.length gives the number of string objects in your array of string objects i.e. 3, but you can access only up to index 2 name[2],
because the array can be accessed from index 0 to name.length - 1 where you get name.length number of objects.

Even while using a for loop you have started with index zero and you should end with name.length - 1. In an array a[n] you can access form a[0] to a[n-1].

For example:

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

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

In your case:

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

for(int i = 0; i<=name.length; i++) {
    System.out.print(name[i] +'\n');
}
冷︶言冷语的世界 2024-11-06 16:49:47

对于给定的数组,数组的长度为 3(即 name.length = 3)。但由于它存储从索引 0 开始的元素,因此它的最大索引为 2。

因此,您应该编写“i<**name.length”,而不是“i**<=name.length” '以避免'ArrayIndexOutOfBoundsException'。

For your given array the length of the array is 3(i.e. name.length = 3). But as it stores element starting from index 0, it has max index 2.

So, instead of 'i**<=name.length' you should write 'i<**name.length' to avoid 'ArrayIndexOutOfBoundsException'.

羁〃客ぐ 2024-11-06 16:49:47

这个简单的问题就讲这么多,但我只是想强调一下 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

So much for this simple question, but I just wanted to highlight a new feature in Java which will avoid all confusions around indexing in arrays even for beginners. Java-8 has abstracted the task of iterating for you.

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]); })

What's the benefit? Well, one thing is the readability like English. Second, you need not worry about the ArrayIndexOutOfBoundsException

故人的歌 2024-11-06 16:49:47

我见过的看似神秘的 ArrayIndexOutOfBoundsExceptions 最常见的情况(即显然不是由您自己的数组处理代码引起的)是并发使用 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"));
  }
}

如果两个线程一起进入 SimpleDateFormat.parse() 方法,您可能会看到 ArrayIndexOutOfBoundsException。请注意 SimpleDateFormat 类 javadoc

确保代码中没有任何位置以并发方式(如 Servlet 或控制器中那样)访问线程不安全类(例如 SimpleDateFormat)。检查 servlet 和控制器的所有实例变量是否存在可疑之处。

The most common case I've seen for seemingly mysterious ArrayIndexOutOfBoundsExceptions, i.e. apparently not caused by your own array handling code, is the concurrent use of SimpleDateFormat. Particularly in a servlet or controller:

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

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

If two threads enter the SimplateDateFormat.parse() method together you will likely see an ArrayIndexOutOfBoundsException. Note the synchronization section of the class javadoc for SimpleDateFormat.

Make sure there is no place in your code that are accessing thread unsafe classes like SimpleDateFormat in a concurrent manner like in a servlet or controller. Check all instance variables of your servlets and controllers for likely suspects.

荒路情人 2024-11-06 16:49:47

由于 i<=name.length 部分,您将收到 ArrayIndexOutOfBoundsExceptionname.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,其中包含组件的数量
数组的。 长度可以是正数或零。

You are getting ArrayIndexOutOfBoundsException due to i<=name.length part. name.length return the length of the string name, which is 3. Hence when you try to access name[3], it's illegal and throws an exception.

Resolved code:

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

It's defined in the Java language specification:

The public final field length, which contains the number of components
of the array. length may be positive or zero.

江湖正好 2024-11-06 16:49:47

数组索引越界异常

这就是这种类型的异常在 Eclipse 中抛出时的样子。红色数字表示您尝试访问的索引。因此,代码如下所示:

myArray[5]

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

int[] intArray = new int[3];

则唯一有效的索引为:

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

如果数组的长度为 1,

int[] intArray = new int[1];

则唯一有效的索引为:

intArray[0]

任何等于数组长度或大于数组长度的整数:界限。

任何小于 0 的整数:超出范围;

PS:如果您希望更好地了解数组并做一些实际练习,这里有一个视频:Java 中的数组教程

Array index out of bounds exception

That's how this type of exception looks when thrown in Eclipse. The number in red signifies the index you tried to access. So the code would look like this:

myArray[5]

The error is thrown when you try to access an index which doesn't exist in that array. If an array has a length of 3,

int[] intArray = new int[3];

then the only valid indexes are:

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

If an array has a length of 1,

int[] intArray = new int[1];

then the only valid index is:

intArray[0]

Any integer equal to the length of the array, or bigger than it: is out of bounds.

Any integer less than 0: is out of bounds;

P.S.: If you look to have a better understanding of arrays and do some practical exercises, there's a video here: tutorial on arrays in Java

救赎№ 2024-11-06 16:49:47

对于多维数组,确保访问正确维度的 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]. lengtha[j].length 相同)。

相反,内部循环应使用 a[i][j].length (或为简单起见,使用 a[0][0].length)。

For multidimensional arrays, it can be tricky to make sure you access the length property of the right dimension. Take the following code for example:

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();
}

Each dimension has a different length, so the subtle bug is that the middle and inner loops use the length property of the same dimension (because a[i].length is the same as a[j].length).

Instead, the inner loop should use a[i][j].length (or a[0][0].length, for simplicity).

司马昭之心 2024-11-06 16:49:47

ArrayIndexOutOfBoundsException 意味着您正在尝试访问不存在或超出该数组范围的数组索引。数组索引从 0 开始,到 length - 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
}

ArrayIndexOutOfBoundsException means that you are trying to access an index of the array that does not exist or out of the bound of this array. Array indexes start from 0 and end at length - 1.

In your case

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

ArrayIndexOutOfBoundsException happens when you are trying to access
the name.length indexed element which does not exist (array index ends at length -1). just replacing <= with < would solve this problem.

for(int i = 0; i < name.length; i++) {
    System.out.print(name[i] +'\n');  // i goes from 0 to length - 1, Correct
}
墨落画卷 2024-11-06 16:49:47

对于任何长度为 n 的数组,数组元素的索引范围为 0 到 n-1。

如果您的程序尝试访问数组索引大于 n-1 的任何元素(或内存) ,那么Java会抛出ArrayIndexOutOfBoundsException

所以这里有两个我们可以在程序中使用的解决方案

  1. 维护计数:

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

    或者其他一些循环语句,例如

    int 计数 = 0;
    while(count < array.length) {
        System.out.println(数组[计数]);
        计数++;
    }
    
  2. 更好的方法是使用 foreach 循环,在这种方法中,程序员无需担心数组中元素的数量。< /p>

    for(String str : array) {
        System.out.println(str);
    }
    

For any array of length n, elements of the array will have an index from 0 to n-1.

If your program is trying to access any element (or memory) having array index greater than n-1, then Java will throw ArrayIndexOutOfBoundsException

So here are two solutions that we can use in a program

  1. Maintaining count:

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

    Or some other looping statement like

    int count = 0;
    while(count < array.length) {
        System.out.println(array[count]);
        count++;
    }
    
  2. A better way go with a for each loop, in this method a programmer has no need to bother about the number of elements in the array.

    for(String str : array) {
        System.out.println(str);
    }
    
最美不过初阳 2024-11-06 16:49:47

ArrayIndexOutOfBoundsException 每当出现此异常时,都意味着您正在尝试使用超出其范围的数组索引,或者用外行术语来说,您请求的索引超出了初始化的索引。

为了防止这种情况,请始终确保您请求的索引不存在于数组中,即如果数组长度为 10,则索引范围必须在 0 到 9 之间

ArrayIndexOutOfBoundsException whenever this exception is coming it mean you are trying to use an index of array which is out of its bounds or in lay man terms you are requesting more than than you have initialised.

To prevent this always make sure that you are not requesting a index which is not present in array i.e. if array length is 10 then your index must range between 0 to 9

苦妄 2024-11-06 16:49:47

ArrayIndexOutOfBounds 意味着您正在尝试索引数组中未分配的位置。

在本例中:

String[] name = { "tom", "dick", "harry" };
for (int i = 0; i <= name.length; i++) {
    System.out.println(name[i]);
}
  • name.length 为 3,因为该数组已使用 3 个 String 对象定义。
  • 当访问数组的内容时,position从0开始。由于有3个项目,因此
  • 当你循环时, 这意味着name[0]=“tom”,name[1]=“dick”和name[2]=“harry” ,由于 i 可以小于或等于 name.length,因此您正在尝试访问不可用的 name[3]

要解决此问题...

  • 在 for 循环中,你可以这样做 i < name.length. 这将阻止循环到 name[3] 并停止在 name[2]

    for(int i = 0; i

  • 每个循环使用一个 for p>

    String[] name = { "tom", "dick", "harry" };
    for(字符串 n : 名称) {
    System.out.println(n);
    }

  • 使用 list.forEach(Consumer action)(需要 Java8)

    String[] name = { "tom", "dick", "harry" };
    Arrays.asList(name).forEach(System.out::println);

  • 将数组转换为流 - 如果您想对数组执行额外的“操作”,例如过滤、转换,这是一个不错的选择文本、转换为地图等(需要 Java8)

    String[] name = { "tom", "dick", "harry" };
    --- Arrays.asList(name).stream().forEach(System.out::println);
    --- Stream.of(name).forEach(System.out::println);

ArrayIndexOutOfBounds means you are trying to index a position within an array that is not allocated.

In this case:

String[] name = { "tom", "dick", "harry" };
for (int i = 0; i <= name.length; i++) {
    System.out.println(name[i]);
}
  • name.length is 3 since the array has been defined with 3 String objects.
  • When accessing the contents of an array, position starts from 0. Since there are 3 items, it would mean name[0]="tom", name[1]="dick" and name[2]="harry
  • When you loop, since i can be less than or equal to name.length, you are trying to access name[3] which is not available.

To get around this...

  • In your for loop, you can do i < name.length. This would prevent looping to name[3] and would instead stop at name[2]

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

  • Use a for each loop

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

  • Use list.forEach(Consumer action) (requires Java8)

    String[] name = { "tom", "dick", "harry" };
    Arrays.asList(name).forEach(System.out::println);

  • Convert array to stream - this is a good option if you want to perform additional 'operations' to your array e.g. filter, transform the text, convert to a map etc (requires Java8)

    String[] name = { "tom", "dick", "harry" };
    --- Arrays.asList(name).stream().forEach(System.out::println);
    --- Stream.of(name).forEach(System.out::println);

帥小哥 2024-11-06 16:49:47

根据您的代码:

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

如果您检查
System.out.print(名称.长度);

你会得到 3;

这意味着你的名字长度是 3

你的循环从 0 运行到 3
应该运行“0到2”或“1到3”

答案

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

According to your Code :

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

If You check
System.out.print(name.length);

you will get 3;

that mean your name length is 3

your loop is running from 0 to 3
which should be running either "0 to 2" or "1 to 3"

Answer

String[] name = {"tom", "dick", "harry"};
for(int i = 0; i<name.length; i++) {
  System.out.print(name[i] +'\n');
}
手长情犹 2024-11-06 16:49:47

数组中的每个项目称为一个元素,每个元素都可以通过其数字索引来访问。如上图所示,编号从 0 开始。例如,第 9 个元素将在索引 8 处访问。

抛出 IndexOutOfBoundsException 表示某种索引(例如数组、字符串或向量)超出范围。

任何数组X,可以从[0到(X.length - 1)]访问

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

IndexOutOfBoundsException is thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

Any array X, can be accessed from [0 to (X.length - 1)]

左岸枫 2024-11-06 16:49:47

我在这里看到所有答案解释如何使用数组以及如何避免索引越界异常。我个人不惜一切代价避免使用数组。我使用 Collections 类,它避免了必须完全处理数组索引的所有愚蠢行为。循环结构与支持代码的集合完美配合,更易于编写、理解和维护。

I see all the answers here explaining how to work with arrays and how to avoid the index out of bounds exceptions. I personally avoid arrays at all costs. I use the Collections classes, which avoids all the silliness of having to deal with array indices entirely. The looping constructs work beautifully with collections supporting code that is both easier to write, understand and maintain.

时光匆匆的小流年 2024-11-06 16:49:47

ArrayIndexOutOfBoundsException 名称本身说明,如果您尝试访问超出数组大小范围的索引处的值,则会发生此类异常。

在你的情况下,你可以从 for 循环中删除等号。

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

更好的选择是迭代数组:

for(String i : name )
      System.out.println(i);

ArrayIndexOutOfBoundsException name itself explains that If you trying to access the value at the index which is out of the scope of Array size then such kind of exception occur.

In your case, You can just remove equal sign from your for loop.

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

The better option is to iterate an array:

for(String i : name )
      System.out.println(i);
七分※倦醒 2024-11-06 16:49:47

如果您使用数组的长度来控制 for 循环的迭代,请始终记住数组中第一项的索引是 0。因此数组中最后一个元素的索引比数组的长度小一。

If you use an array's length to control iteration of a for loop, always remember that the index of the first item in an array is 0. So the index of the last element in an array is one less than the array's length.

苄①跕圉湢 2024-11-06 16:49:47

此错误发生在运行循环超出限制次数时。让我们考虑这样的简单示例,

class demo{
  public static void main(String a[]){

    int[] numberArray={4,8,2,3,89,5};

    int i;

    for(i=0;i<numberArray.length;i++){
        System.out.print(numberArray[i+1]+"  ");
    }
}

首先,我将一个数组初始化为“numberArray”。然后,使用 for 循环打印一些数组元素。当循环运行'i'次时,打印(numberArray[i+1]元素..(当i值为1时,打印numberArray[i+1]元素。)..假设,当i=(numberArray. length-2),打印数组的最后一个元素。当“i”值转到(numberArray.length-1)时,没有打印值。此时,会发生“ArrayIndexOutOfBoundsException”。我希望你能得到想法。谢谢!

This error is occurs at runs loop overlimit times.Let's consider simple example like this,

class demo{
  public static void main(String a[]){

    int[] numberArray={4,8,2,3,89,5};

    int i;

    for(i=0;i<numberArray.length;i++){
        System.out.print(numberArray[i+1]+"  ");
    }
}

At first, I have initialized an array as 'numberArray'. then , some array elements are printed using for loop. When loop is running 'i' time , print the (numberArray[i+1] element..(when i value is 1, numberArray[i+1] element is printed.)..Suppose that, when i=(numberArray.length-2), last element of array is printed..When 'i' value goes to (numberArray.length-1) , no value for printing..In that point , 'ArrayIndexOutOfBoundsException' is occur.I hope to you could get idea.thank you !

青春有你 2024-11-06 16:49:47

您可以在函数式风格中使用Optional来避免NullPointerExceptionArrayIndexOutOfBoundsException

String[] array = new String[]{"aaa", null, "ccc"};
for (int i = 0; i < 4; i++) {
    String result = Optional.ofNullable(array.length > i ? array[i] : null)
            .map(x -> x.toUpperCase()) //some operation here
            .orElse("NO_DATA");
    System.out.println(result);
}

输出:

AAA
NO_DATA
CCC
NO_DATA

You can use Optional in functional style to avoid NullPointerException and ArrayIndexOutOfBoundsException :

String[] array = new String[]{"aaa", null, "ccc"};
for (int i = 0; i < 4; i++) {
    String result = Optional.ofNullable(array.length > i ? array[i] : null)
            .map(x -> x.toUpperCase()) //some operation here
            .orElse("NO_DATA");
    System.out.println(result);
}

Output:

AAA
NO_DATA
CCC
NO_DATA
国粹 2024-11-06 16:49:47

当您尝试访问不存在的数组的索引时,会发生 ArrayIdexOutOfBoundException。在您的场景中,当 i = 3 时,您尝试检索名称数组的第三个索引。但名称数组保存的值最多为第二个索引。

由于数组的第三个索引处没有值,因此抛出此异常。

An ArrayIdexOutOfBoundException occurs when you try to access an index of an array which does not exists. In your scenario when i = 3, you try to retrieve the 3rd index of the names array. But names array holds values up to 2nd index.

Since there are no value at 3rd index of the array, This Exception is thrown.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文