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

后端 未结 5 580

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 08:59

    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.

    0 讨论(0)
  • 2021-02-04 09:00

    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.

    0 讨论(0)
  • 2021-02-04 09:02

    I found a solution too. It was next.

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

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

    0 讨论(0)
  • 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<T> lit = list.listIterator(index);
        current = lit.hasNext()?lit.next():null;
        previous = lit.hasPrevious()?lit.previous():null;
    }
    
    0 讨论(0)
  • 2021-02-04 09:20

    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));
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题