Reverse iteration through ArrayList gives IndexOutOfBoundsException

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

提交回复
热议问题