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

后端 未结 5 585

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

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-04 09:00

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

    ListIterator 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.

提交回复
热议问题