Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For-each loop still shows the original array after reversing

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading