2012-11-06 15 views
0

什麼是最佳實踐和解決方案檢查「索引超出界限」下面的解決方案的工作,但感覺很hacky。有沒有更好的選擇?接下來在數組和索引超出範圍

public void nextPerson(int index){ //Index is the current location in the arraylist 
    try{ 
     System.out.println(thePeople.get(index++)); 
    } 
    catch (IndexOutOfBoundsException e){ 
     System.out.println("At the end"); 
    } 
} 

回答

0

我想通了,通過具有一個局部變量來跟蹤Arraylist指數。我能夠有兩種方法來處理ArrayList的移動想法。有一個用於輸出當前位置。

if(arrayPosition < thePeople.size() - 1) 
0

編輯:Java是通過值。這意味着,如果將「index」變量傳遞給函數,則外部變量不會受到函數內執行的更改的影響。

所以,你必須保證指數的VAR類範圍的,像列表...

public void nextPerson(){ 
    if (index>=0 && index<thePeople.size()) 
     System.out.println(thePeople.get(index++)); 
    } else { 
     System.out.println("At the end"); 
    } 
} 

還是要通過它,並將其返回

public int nextPerson(int index){ 
     if (index>=0 && index<thePeople.size()) 
      System.out.println(thePeople.get(index++)); 
     } else { 
      System.out.println("At the end"); 
     } 
     return index; 
    } 

同樣會爲previouPerson ,只需使用index--;

順便說一句,如果你保持指數消費類,這個對象之外,你可以得到整個列表,並在消費類遍歷它...

+0

有了您的解決方案,使用previousPerson方法的正確方法是什麼? – Melky

+0

完全一樣,但有索引 - '...我建議你發佈一個更大的代碼摘錄,看看是否有可能重新設計一下 –

+0

我的微不足道的想法是使用'index - '但它沒有工作。 '私人ArrayList thePeople;'我只有一個基本的構造函數,我將它們添加到數組中。 – Melky