Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 elements of this element. Now my code is huge. It costs a lot if I rewrite it with:

for (int i = 0; i < list.size(); i++){
  ...
}
like image 498
nomnom Avatar asked Nov 08 '13 02:11

nomnom


1 Answers

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.

like image 74
Jack Avatar answered Oct 13 '22 17:10

Jack