簡體   English   中英

ArrayIndexOutOfBound異常

[英]ArrayIndexOutOfBound Exception

這是我從綁定異常中獲取索引的代碼,但我不明白為什么,

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

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

我收到java.lang.ArrayIndexOutOfBoundsException:-1 at item = array [index]; 我不知道哪里出了問題。 誰能幫忙。

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

應該

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

在最后一個循環中,運行索引為0,這對於條件而言為true。 然后遞減為-1,然后嘗試在該位置訪問數組元素。

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

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

在這里,您首先要遞減index然后再訪問該索引處的element index = 0當您第一次將索引遞減時,它達到-1array[-1]給您java.lang.ArrayIndexOutOfBoundsException

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

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

這應該為您工作。

在將索引用作數組中對象的指針之前,您的while循環遞減。 這將導致指向-1,並將為您提供空指針異常。

嘗試將減量放在item = array [index]之后;

這應該工作

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM