How can I access the previous / next item in an ArrayList?

I iterate over an ArrayList as follows:

for (T t : list){ ... } 

When I did this, I never thought that I needed to access the previous and subsequent elements of this element. Now my code is huge. It costs a lot if I rewrote it with:

 for (int i = 0; i < list.size(); i++){ ... } 
+10
java arraylist for-loop
source share
5 answers

I think I found the solution just really, but I can’t delete this post already because it has answers ..

I just added T t = list.get(i); in the second for loop, all other codes remained unchanged.

0
source share

No, the for-each loop is designed to abstract Iterator<E> , which is under the hood. Access to it will allow you to extract the previous item:

 ListIterator<T> it = list.listIterator(); while (it.hasNext()) { T t = it.next(); T prev = it.previous(); } 

but you cannot do it directly with each of them.

+21
source share

As an answer to the heading, not to the question (taking into account parallel operations) ...

 T current; T previous; { ListIterator<T> lit = list.listIterator(index); current = lit.hasNext()?lit.next():null; previous = lit.hasPrevious()?lit.previous():null; } 
+4
source share

You can access any element in an ArrayList using the get (index) method.

 import java.util.ArrayList; public class Test { public static void main(String[] args) { ArrayList<Integer> array = new ArrayList<Integer>(); array.add(1); array.add(2); array.add(3); for(int i=1; i<array.size(); i++){ System.out.println(array.get(i-1)); System.out.println(array.get(i)); } } } 
+1
source share

I also found a solution. It was next. For the following: letters.get (letters.indexOf (')') +1); For the previous one: letters.get (letters.indexOf (')') -1)

0
source share

All Articles