Everyone! I faced this strange behaviour of Java arrays. I cannot figure out why sampleArray is changing along with class' array? I find this unnatural.
public class Runner {
public static void main(String[] args) {
int sampleArray[] = new int[]{5, -1, 9 ,7 ,3 ,2 ,11 ,0 ,-7 ,6 , 10 ,9};
SortArray testArray = new SortArray(sampleArray);
System.out.println("Initial array is:");
System.out.println(testArray.toString());
testArray.sortArray();
System.out.println("Sorted by Bubbles method array is:");
System.out.println(testArray.toString());
System.out.println("Initial array is");
for (int i = 0; i<sampleArray.length; i++) {
System.out.print(sampleArray[i]+ " ");
}
}
public class SortArray {
private int anArray[];
SortArray (int inputArray[]) {
this.anArray = inputArray;
}
// Classic Bubbles sorting
public void sortArray () {
int arrayLength = this.anArray.length;
for (int i = arrayLength; i > 0; i--) {
for (int j = 0; j < i-1; j++) {
if (anArray[j+1]<anArray[j]) {
int tempVariable = anArray[j];
anArray[j] = anArray[j+1];
anArray[j+1] = tempVariable;
}
}
}
}
@Override
public String toString() {
String arrayString = "";
for (int i = 0; i<anArray.length; i++) {
arrayString = arrayString + anArray[i]+" ";
}
return arrayString;
}
}
After all I keep getting:
Initial array is:
5 -1 9 7 3 2 11 0 -7 6 10 9
Sorted by Bubbles method array is:
-7 -1 0 2 3 5 6 7 9 9 10 11
Initial array is
-7 -1 0 2 3 5 6 7 9 9 10 11
Process finished with exit code 0
So we see that initial array is changing as well. Why is this happening? It seems to be illogical as I never assign sampeArray another sequence and never change it directly in the code. But it's true. What to do in order to keep the initial array unaffected?