I iterate through an ArrayList this way:
for (T t : list){
...
}
When I did this, I never thought I had to access the previous and next eleme
I think I found the solution it is simple in fact, but I cannot delete this post already because it has answers..
I just added T t = list.get(i);
in the second for-loop, all other code remains unchanged.
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)
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;
}
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));
}
}
}