Reverse iteration through ArrayList gives IndexOutOfBoundsException

前端 未结 9 2142
广开言路
广开言路 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 03:15

    If the lists are fairly small so that performance is not a real issue, one can use the reverse-metod of the Lists-class in Google Guava. Yields pretty for-each-code, and the original list stays the same. Also, the reversed list is backed by the original list, so any change to the original list will be reflected in the reversed one.

    import com.google.common.collect.Lists;
    
    [...]
    
    final List myList = Lists.newArrayList("one", "two", "three");
    final List myReverseList = Lists.reverse(myList);
    
    System.out.println(myList);
    System.out.println(myReverseList);
    
    myList.add("four");
    
    System.out.println(myList);
    System.out.println(myReverseList);
    

    Yields the following result:

    [one, two, three]
    [three, two, one]
    [one, two, three, four]
    [four, three, two, one]
    

    Which means that reverse iteration of myList can be written as:

    for (final String someString : Lists.reverse(myList) {
        //do something
    }
    

提交回复
热议问题