Reverse iteration through ArrayList gives IndexOutOfBoundsException

前端 未结 9 2134
广开言路
广开言路 2021-02-05 02:13

When I reverse iterate over an ArrayList I am getting a IndexOutOfBoundsException. I tried doing forward iteration and there is no problem. I expect and know that there are five

相关标签:
9条回答
  • 2021-02-05 02:53

    You can reverse by one line that is

    Collections.reverse(list);

    ArrayList arrayList = new ArrayList();
    
    arrayList.add("A");
    arrayList.add("B");
    
    System.out.println("Before Reverse Order : " + arrayList);
    
    Collections.reverse(arrayList);
    
    System.out.println("After Reverse : " + arrayList);
    

    Output

    Before Reverse Order : [A, B]
    After Reverse : [B, A]
    
    0 讨论(0)
  • 2021-02-05 02:56

    Java arrays are zero-indexed. You will have to set j = list.size() - 1 and continue until j = 0.

    0 讨论(0)
  • 2021-02-05 03:03

    The most elegant way is to reverse the array and then use a direct (or even implicit) iterator :

    Collections.reverse(arrayList);
    for (Object item : arrayList) {
        ...
    }
    
    0 讨论(0)
  • 2021-02-05 03:06

    I know this is an old question, but Java contains a Collections.reverse( List<T> ) method. Why wouldn't you just reverse it and do forward iteration?

    0 讨论(0)
  • 2021-02-05 03:07

    Avoid indexes altogether? How about:

    for (ListIterator iterator = list.listIterator(list.size()); iterator.hasPrevious();) {
      final Object listElement = iterator.previous();
    }
    
    0 讨论(0)
  • 2021-02-05 03:13

    Start the iteration at list.size() - 1 because array (or ArrayList) elements are numbered from 0 up through 1 less than the size of the list. This is a fairly standard idiom:

    for (int j = list.size() - 1; j >= 0; j--) {
        // whatever
    }
    

    Note that your forward iteration works because it stops before reaching list.size().

    0 讨论(0)
提交回复
热议问题