Home > Net >  For-each loop still shows the original array after reversing
For-each loop still shows the original array after reversing

Time:12-18

I was simply doing a test to see the difference between a for-each loop and a regular for loop. I initialized an array and reversed it, and then tried to print it with both loops, however, only the regular for loop printed out the reversed array.

public static void main(String[] args) {
    int[] list1 = {0,1,2,3,4,5,6,7,8,9};
    int[] list2 = reverse(list1);
    
    for(int i=0;i<list2.length;i  ) {
        System.out.print(list2[i]);
    }
    System.out.println();
    for(int i:list2) {
        System.out.print(list2[i]);
    }
}

static int[] reverse(int[] a) {
    int[] temp = new int[a.length];
    for(int i=0,j=a.length-1;i<a.length;i  ,j--) {
        temp[i]=a[j];
    }
    return temp;
}

I tried using the Arrays.toString method of the Arrays class to print out the list, and it also prints out the reversed list, both before and after the for-each loop.

CodePudding user response:

A for-each loop iterates over the elements rather than their indices. Change list2[i] to i and you'll see the reversed list:

for (int i: list2) {
    System.out.print(i);
}

Debugging tip: Mixing up indices and elements is a common mistake. A good way to make it more obvious which is which is to avoid using elements that start at 0 and count up, because then they look just like indices. Next time try, say:

int[] list1 = {11, 22, 33, 44, 55, 66, 77, 88, 99};
  • Related