2015-06-29 19 views
3

我正在研究Java應用程序,並且我有一個int ArrayList如何使用java獲取當前和下一個數組列表索引

我收到了當前的ArrayList索引,但請指導我如何通過使用for循環獲取下一個ArrayList索引。

我試圖做到這一點使用下面的代碼,但我得到一個ArrayIndexOutOfbound例外:

ArrayList<Integer> temp1 = new ArrayList<Integer>(); 

假設的ArrayList是有以下元素。

temp1={10,20,30} 

我們如何使用循環來實現這一目標:

for(int i=0;i<arraylist.size;i++)<--size is 3 
{ 
    int t1=temp1.get(i); 
    int t2=temp1.get(i+1); // <---here i want next index 
} 

我想要做加法的第一個-10和20 第二-20和30 3-30和10

有沒有可能做到這一點?它應該適用於任何尺寸的ArrayList。我願意以不同的方式來實現這一目標。

+2

將't2 = temp1.get(i + 1)'改爲't2 = temp1.get((i + 1)%arrayList.size())'。 – saka1029

+0

最簡單的問題已經在StackOverflow中有答案。嘗試http://stackoverflow.com/questions/19850468/how-can-i-access-the-previous-next-element-in-an-arraylist – Zon

回答

7

如果對於要添加第一個索引值的最後一個索引,應該使用next position索引作爲 - (i+1)%arraylist.size()。此外,對於ArrayList大小是一個函數,而不是一個變量。

所以循環會 -

for(int i=0;i<arraylist.size();i++)<--size is 3 
{ 
    int t1=temp1.get(i); 
    int t2=temp1.get((i+1)%arraylist.size()); 
} 
+0

非常感謝你....它爲我工作.. – user3667820

+0

很高興它對你有效。 –

0

修改代碼snippet.Check以下

  import java.util.ArrayList; 

      public class Main { 


       public static void main(String[] args) { 
        ArrayList<Integer> temp1 = new ArrayList<Integer>(); 
        temp1.add(10); 
        temp1.add(20); 
        temp1.add(30); 
          for(int i=0;i<temp1.size()-1;i++) 
          { 
           int t1=temp1.get(i); 
           int t2=temp1.get(i+1); 
           System.out.println(t1+t2); 
           if(i==temp1.size()-2){ 
            System.out.println(temp1.get(0)+temp1.get(temp1.size()-1)); 
           } 
          } 
       } 
      } 

輸出:

相關問題