简体   繁体   中英

ArrayIndexOutOfBound Exception

This is the code where I am getting index out of bound exception and I don't understand why,

 int index = array.length - 1;
 E item = array[index];

  while (item == null && index >= 0) {
  index--;
  item = array[index];
  }

I am getting java.lang.ArrayIndexOutOfBoundsException: -1 at item = array[index]; I don't know where I went wrong. Could anyone please help.

while (item == null && index >= 0) {
  index--;
  item = array[index];
}

should be

while (item == null && index >= 0) {
  item = array[index--];
}

In the last loop run index is 0 which is true for the condition. Then you decrement to -1 and try to access the array element at that position.

int index = array.length - 1;
 E item = array[index];

  while (item == null && index >= 0) {
  index--;
  item = array[index];
  }

Here you are first decrementing the index before you access the element at that index. When index = 0 as you first decrement the index it reaches -1 and array[-1] gives you java.lang.ArrayIndexOutOfBoundsException

 int index = array.length - 1;
     E item = array[index];

      while (item == null && index >= 0) {      
      item = array[index];
      index--;
      }

This should work for you.

Your while loop is decrement before using the index as a pointer to the object in the array. This will result in pointing at -1 and will give you the null pointer exception.

Try placing the decrement after item = array[index];

This should work

int index = array.length - 1;
 E item = array[index];

  while (item == null && index > 0) {
  index--;
  item = array[index];
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM