当前位置: 动力学知识库 > 问答 > 编程问答 >

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

问题描述:

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

网友答案:
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];
}

See also:

  • The Java Tutorials - Language Basics - Arrays

Update: as per your code snippet,

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++) {
网友答案:

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++) 
                 ^
网友答案:

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];
网友答案:

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");
}
网友答案:

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 eachother, 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 have 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 index 0).

An ArrayIndexOutOfBoundsException is caused by trying to retrive a "box" that does not exist, by passing an index that is higher than the index of 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] //waay 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 neccessary.

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];
}
网友答案:

The most common case I've seen for seemingly mysterious ArrayIndexOutOfBoundsExceptions, ie apparently not cause 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 are you accessing thread unsafe classes like SimpleDateFormat in a concurrent manner like a servlet or controller. Check all instance variables of your servlets and controllers for likely suspects.

网友答案:

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 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.Better way go with For Each loop, in this method programmer has no needs to bother about the number of elements in the array.

for(String str : array) {  
    System.out.println(str);  
}
网友答案:

You could not iterate or store more data than length of your array. In this case you could do like this:

for (int i = 0; i <= name.length - 1; i++) {
    // ....
}

or this:

for (int i = 0; i < name.length; i++) {
    // ...
}
网友答案:

In this section, you access the elements from outside of the loop:

for(int i=0; i<list.size; i++)
{

}

In this case the For loop of condition is completed, and again you retrieve the value from list by using i++: Such that you get the ArrayindexOutOfBoundexception.

It would be better to go with a ForEach loop - where all these issues will be take care of:

for(String str : list)
{
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: