title: how to iterate over consecutive pairs in arrayList
body: <p>I want to create a loop that iterates through an ArrayList of objects.</p>
  
  <pre><code>for (int i = 0,  k=i+1; k &lt; arr.size(); i++) { 
       int tprice;
       tprice=0;
       if (arr.get(i).getID()=arr.get(i+1).getID()) {
          tprice = arr.get(i).getPrice() + arr.get(i+1).getPrice();
       }
       else {
             if (tprice!=0) {
                System.out.println(tprice);
                }
             else {
                System.out.println(arr.get(i).getDuration());
                }
         }
      }
  </code></pre>
  
  <p>I want to compare element <code>i</code> to element <code>i+1</code> of the ArrayList, without creating a nested for loop as I am not interested in all the permutations. (e.g, <code>1-&gt;2</code> then <code>2-&gt;3</code>, not <code>1-&gt;2</code> then <code>1-&gt;3</code>)</p>
  
  <p>However, my line of code always causes an error because index <code>k</code> at the end of the loop is referencing an out-of-bounds index (or the equivalent for ArrayList).</p>
  
  <p>Say i have three arrays : i=0 compares to i=1, i=1 compares to i=2, i=2 compares to i=3 but throws back an error since it doesn't exist.</p>
  
  <p>Is there any way to overcome this? It seems silly, but I couldn't find anything about it across the forums.</p>
  
  <p>exemple hardcode: </p>
  
  <pre><code>         arr.add(new object(444,24))  // 444 is ID, 24 is Price
           arr.add(new object(444,29))  // 444 is ID, 29 is Price
           arr.add(new object(121,33))  // ...
  </code></pre>
  
  <p>wanted outcome : </p>
  
  <pre><code>       53
         53
         33
  </code></pre>
  
  <p>side-question : if i am dealing with the same ID, i would ideally wish to print only once. Is there anyway to do so?</p>