2

I've tried this code but I am unsure as to why it does not work:

    String[] arr = {"A", "B", "C", "D", "E"};//AD
    String[] arr2 = arr;
    int last = arr.length-1;
    int first = 0;
    int size = arr.length;
    while (first < size) {
        arr2[first] = arr[last];
        last--;
        first++;
    }
    System.out.print(Arrays.toString(arr2));

Can anybody help?

7
  • 2
    String[] arr2 = arr; doesn't make a copy. That's still the same array. Commented Oct 2, 2017 at 0:07
  • "String[] arr2 = arr;" - What Harry Potter style magic do you expect here to happen? Commented Oct 2, 2017 at 0:07
  • Just make a brand new array of the same length and fill it backwards Commented Oct 2, 2017 at 0:08
  • @tom omg I forgot this isn't python and the array changes even after you copy it.... Commented Oct 2, 2017 at 0:09
  • 2
    That's not correct. The arrays wouldn't change if you would actually copy them. Commented Oct 2, 2017 at 0:09

1 Answer 1

2

This line does not do what you think it does: String[] arr2 = arr. This is simply pointing the variable arr2 at the same object reference as arr. So changes in one will show up in the other, since they're effectively the same thing.

In order to reverse an array, you need to iterate through the array and copy the values to your reversed array.

String[] arr = { "A", "B", "C", "D", "E" };
String[] reversed = new String[arr.length];

for(int i = 0, j = arr.length-1 ; i < arr.length; i++, j--) {
  reversed[j] = arr[i];
}
Sign up to request clarification or add additional context in comments.

4 Comments

You could do it in place
Feel free to add your own answer showing how to reverse an array in place into a new variable without modifying the original.
Wow, I didn't even know you could do that with a for loop, so cool!
I feel like to do it in place with the same variable you would have to copy the value that you are going to be switching into a temp variable and then put it back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.