I’m trying to shift all values in an array with a given number. For example array {1,2,3,4,5} with 1 shift has to become {5,1,2,3,4}. This is tested with JUnit.
The JUnit test is this:
@Test
public void shift1(){
double[] row = {1.0,2.0,3.0,4.0,5.0};
int amount= 1;
ArrayOperations.shift(row, amount);
Assert.assertEquals(5.0, row [0]);
Assert.assertEquals(1.0, row [1]);
Assert.assertEquals(2.0, row [2]);
Assert.assertEquals(3.0, row [3]);
Assert.assertEquals(4.0, row [4]);
}
My method is this:
public static void shift(double[] row, int amount) {
double[] newRow= new double[row.length];
for (int i = 0; i < newRow.length; i++) {
newRow[(i + amount) % row.length] = row[i];
}
row= newRow;
}
Now this test fails for any unknown reason. I had this problem in programming class and even my teacher didn’t find out why. When I debug this, the array is modified correctly resulting in {5,1,2,3,4}. But the JUnit fails… This code however works:
public static void shift(double[] row, int amount) {
double[] newRow= new double[row.length];
for (int i = 0; i < newRow.length; i++) {
newRow[(i + amount) % row.length] = row[i];
}
for (int i = 0; i < newRow.length; i++) {
row[i] = newRow[i];
}
}
Anyone know why? row= newRow; is correct right? Even the debugger says it’s changed correctly… So why does the test fail with the first implementation, but not with the second?
No, it doesn’t work because you’re confused how parameters work in Java. This has nothing to do with JUnit, or arrays specifically. It has everything to do with parameters.
No, it’s not. That just sets the value of the parameter, which is just a local variable within the method. It does nothing to the caller’s variable, which is what you were expecting.
A simpler example:
All arguments are passed by value in Java… although you need to understand that for reference types, those values are references (not objects).
I suggest you find a good Java tutorial or book, and read up more on parameter passing.