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

后端 未结 5 586

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:15

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

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

提交回复
热议问题