Reverse iteration through ArrayList gives IndexOutOfBoundsException

前端 未结 9 2130
广开言路
广开言路 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

    The list.size() is past the last allowable index.

    for(int j = list.size() - 1; j >= 0; j--) {
      System.out.println(list.get(j));
    }
    
    0 讨论(0)
  • 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<String> myList = Lists.newArrayList("one", "two", "three");
    final List<String> 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
    }
    
    0 讨论(0)
  • 2021-02-05 03:15

    You can do this if you are comfortable with foreach loop.

    List<String> list = new ArrayList<String>();
    list.add("ABC");
    list.add("DEF");
    list.add("GHI");
    
    ListIterator<String> listIterator = list.listIterator(list.size());
    
    while(listIterator.hasPrevious()){
      System.out.println(listIterator.previous());
    }
    
    0 讨论(0)
提交回复
热议问题