public static void reverse(int[] arr)
{
int[] a= arr;
int index=a.length-1;
for (int i=0; i<a.length; i++){
System.out.println(ArrayUtil.toString(a));
if (index>=0){
arr[index]=a[i];
index--;
}
}
}
So, I'm trying to reverse the order of the elements in a given array. I declare another temporary array "a" that's the same as the given array. However, when going through the loop to reverse the order or elements, somehow the array "a" is also being changed. I don't see how this is possible. int[] arr in this case was [14,2,19,3,15,22,18,7] and the end result is [14,2,19,3,3,19,2,14] for both []arr and []a. Help would be really appreciated, thank you.
Also, I'm new to this forum, so I'm sorry if I didn't follow proper format
THANK YOU VERY MUCH for everyone who contributed! Amazing and fast responses!
int[] a= arr;does ?a. If you want the same length new array, donew int[arr.length].aandarrpoint to the same memory location. So when one changes so does the other.