Can someone explain what's happening here when trying to reverse this arrayList? I am just trying to understand

I am trying to understand what's happening here when trying to reverse this arraylist, why does decreasing the size by -1 and why does decreasing i by -- reverse the order? I understand what happens when i loop over an ArrayList, but i don't understand what happens when i try to reverse the order, can someone explain this to me? I am fairly new to programming.

ArrayList<String> colorsArray = new ArrayList<>();
        colorsArray.add("Blue");
        colorsArray.add("Black");
        colorsArray.add("Yellow");
        colorsArray.add("Brown");
        colorsArray.add("White");

        //prints arraylist..
        for(int i =0; i < colorsArray.size(); i++){
            System.out.println("Array List: " + colorsArray.get(i));
        }

        //This prints ArrayList in reverseOrder...
        for(int i = colorsArray.size() - 1;  i >= 0; i --){
            System.out.println("Array List Reverse Order: " + colorsArray.get(i));
        }

    }

It's not "reversing the array list". It's simply printing the contents in reverse order.

Your first loop counts up from 0 to N-1, where N is the size of the list. Your second loop counts down from N-1 to 0.

In each loop, you then print the element of the list that is at the position indicated by the current value of the count (which is in your variable named i).

That is all.


ArrayList is an ordered list. This means that every position of a list is numbered, starting from 0, consecutively until the size of the list minus 1 (because it starts by 0, not 1).

So, your list elements will have the following indexes inside the list.

0-Blue

1-Black

2-Yellow

3-Browm

4-Whote

This way list.get(0) returns Blue, and list.get(3) returns Brown.

In the first loop you go through all elements of the list from 0 to 4, but in the second one you go from 4 to 0, that's why it prints it in reverse order.