2015-06-29 21 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)); 
           } 
          } 
       } 
      } 

输出:

相关问题