Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current and Next arraylist index in for loop using java

Tags:

java

arraylist

I am working on a Java application and I am having one int ArrayList.

I am getting current ArrayList index but please guide me on how to get the next ArrayList index by using a for loop.

I'm trying to do this using the code below but I'm getting an ArrayIndexOutOfbound exception:

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

suppose arraylist is having below elements.

temp1={10,20,30}

How can we use for loop to achieve 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 do addition of 1st-10 and 20 2nd-20 and 30 3rd-30 and 10

Is it possible to achieve this? It should work for any size of ArrayList. I am open to different approaches to achieve this.

like image 591
user3667820 Avatar asked Nov 27 '25 20:11

user3667820


1 Answers

If for the last index you want to add it with the first index value, you should use the next position index as - (i+1)%arraylist.size() . Also, for an ArrayList size is a function, not a variable.

So the loop would 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());
}
like image 57
Anand S Kumar Avatar answered Nov 29 '25 09:11

Anand S Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!