Reputation: 7
I was trying to make a short code to switch the first and last values in an array and output a new array identical to the first array but with those values switched. After trying a few times, I realized my first (original) array kept switching its [0] value, and I can't tell why. This is the code.
import java.util.Arrays;
public class testing {
public static void main(String[] args) {
int[] original={1,2,3,4};
int[] switched=original;
switched[0]=original[original.length-1];
switched[switched.length-1]=original[0];
System.out.println(Arrays.toString(switched));
}
}
I wanted the output to be [4,2,3,1], but I always get [4,2,3,4].
Upvotes: 0
Views: 62
Reputation: 23029
There is some magic you should know :).
In this line : int[] original={1,2,3,4};
you create array {1,2,3,4} and you store REFERENCE to it in your variable original
In this line : int[] switched=original;
you copy the value of original
which is REFERENCE to that array into the variable switched
.
Now, you have two variables which are both referencing to the same array!
To create new array with same values, you can use this :
int [] switched = (int[])original.clone();
Upvotes: 0
Reputation: 5857
Because switched
and original
pointing to the same object.
Do:
import java.util.Arrays;
public class testing {
public static void main(String[] args) {
int[] original={1,2,3,4};
int[] switched={1,2,3,4};
switched[0]=original[original.length-1];
switched[switched.length-1]=original[0];
System.out.println(Arrays.toString(switched));
}
}
Upvotes: 0
Reputation: 240870
both are reference to same array
initially
1,2,3,4
after
switched[0]=original[original.length-1];
4,2,3,4
after
switched[switched.length-1]=original[0];
4,2,3,4
Upvotes: 1