How to get the current and next index of an arraylist for a loop using java

I am working on a Java application and I have one int ArrayList

.

I am getting the current ArrayList

index, but please tell me how to get the next index ArrayList

using a loop for

.

I am trying to do it using the code below, but I am getting an exception ArrayIndexOutOfbound

:

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

      

let's say the arraylist has below elements.

temp1={10,20,30}

      

How can we use to loop for this:

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
}

      

I want to make the addition of 1st and 10th 2-20 and 30 3-30 and 10

Can this be achieved? It should work for any size ArrayList

. I am open to different approaches to achieve this.

+3


source to share


2 answers


If for the last index you want to add it with the first index value, you must use the next position

as index - (i+1)%arraylist.size()

. Also, for, ArrayList

size is a function, not a variable.

So the loop will be -



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

      

+7


source


changed your code snippet. Note the following

            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));
                               }
                           }
                }
            }

      

Output:



thirty

50

40

0


source







All Articles