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

As an answer to the title, rather than the question(with considerations to concurrent operations)...

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

No, the for-each loop is meant to abstract the Iterator<E> which is under the hood. Accessing it would allow you to retrieve the previous element:

ListIterator<T> it = list.listIterator();

while (it.hasNext()) {
  T t = it.next();
  T prev = it.previous();
}

but you can't do it directly with the for-each.


I found a solution too. It was next.

For next: letters.get(letters.indexOf(')')+1)

For previous: letters.get(letters.indexOf(')')-1)


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

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