[英]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]; 我收到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. 在最后一个循环中,运行索引为0,这对于条件而言为true。 Then you decrement to -1 and try to access the array element at that position.
然后递减为-1,然后尝试在该位置访问数组元素。
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. 在这里,您首先要递减
index
然后再访问该索引处的element
。 When index = 0
as you first decrement the index it reaches -1
and array[-1]
gives you java.lang.ArrayIndexOutOfBoundsException
当
index = 0
当您第一次将索引递减时,它达到-1
而array[-1]
给您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. 在将索引用作数组中对象的指针之前,您的while循环递减。 This will result in pointing at -1 and will give you the null pointer exception.
这将导致指向-1,并将为您提供空指针异常。
Try placing the decrement after item = array[index]; 尝试将减量放在item = array [index]之后;
This should work 这应该工作
int index = array.length - 1;
E item = array[index];
while (item == null && index > 0) {
index--;
item = array[index];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.