Guy Stimpson Guy Stimpson - 4 months ago 9
Java Question

How to exchange columns of data in a Java array

I'm not sure if I've been staring at the screen for too long, I'm immensely stupid, or there's something odd going on.

I have a n*m array of doubles,

Home.data
. I'm trying to exchange the data from column 0 with that of a user selected column, so the two are effectively interchanged. Here is the code:

public class ChangeOrdinate {
public void rearrange(int index){
double[][] tempdata1 = Home.data;
double[][] tempdata2 = Home.data;

for(int i = 0; i < Home.data.length; i++){
Home.data[i][index] = tempdata1[i][0];
}
for(int i = 0; i < Home.data.length;i++){
Home.data[i][0] = tempdata2[i][index];
}
}
}


However, this code only manages to move the data from column 0 to the 'index' column. The data from the 'index' column is never returned to column 0.

I have tried
System.out.println(tempdata2[I][index]);
either side of the expression in the first loop, and it appears that the data in
tempdata2
is being altered, despite there being no reference to it.

I have absolutely no idea wtf is going wrong. Is there anything obvious I'm missing? I'm not that much of a noob, so either it's late and I've not had enough coffee, or it's late and I've had too much coffee.

Many thanks in advance,

G

Answer

it appears that the data in tempdata2 is being altered, despite there being no reference to it.

Any changes to the reference of Home.data also affect the reference of the two temp arrays. So, those aren't copies, those all point to the same array in memory.

As for swapping numbers, the problem is you assign a=b, then try to assign b=a (because the reference is the same). Which ends up a noop of b=b

You can use one loop to swap, as well

    for(int i = 0; i < Home.data.length; i++){
        int tmp = Home.data[i][index];
        Home.data[i][index] = Home.data[i][0];
        Home.data[i][0] = tmp;
    }
Comments