views:

57

answers:

2

I am not sure if this is Java behaviour or rogue GWT behaviour. But here goes.

I have a class for 2D vectors, called Vector2. In my program I do some simulation of 2D particles represented by instances of this class. I have two arrays of Vector2, m_x and m_oldx that are members of another class, with a function that does some processing. Part of this function is the following, and I'm awfully confused by its behaviour:

Vector2 old = m_x[i];

Vector2 test = new Vector2(9.0f,9.0f);
m_x[i] = test;

// 1: at this point, m_x[i]'s values are 9.0,9.0
m_oldx[i] = old;
// 2: at this point, m_x[i]'s values are 100.0,100.0 - their original values before I assigned test to m_x[i]!

So basically, it appears that by virtue of the fact that I assign old to the m_oldx array, m_x[i]'s value gets reset to its original value! It's no longer equal to the test variable I assigned to it earlier.

Surely that can't be right? But this is what's happening for me. I should say again that I am using GWT here - i.e. this code gets compiled down to Javascript by Google's compiler. Is this regular java behaviour or is GWT doing something wrong? Thanks for any help...tearing my hair out :(

+2  A: 

It appears that m_x and m_oldx are in fact the same array, so modifying one variable modifies the other as well. You probably did this earlier:

m_oldx = m_x;

Because of Java's object reference semantics doing m_oldx = m_x doesn't copy the array, it simply sets m_oldx to point to the same array as m_x. If you want to copy it you will need to do so explicitly:

m_oldx = Arrays.copyOf(m_x, m_x.length);
John Kugelman
+4  A: 

When problems like this occur, my first thought is that m_x and m_oldx have been set equal to one another at some point, as Java passes instances to variables by value rather than by creating a copy. For instance, if at any point you have:

m_oldx = m_x;

or

m_x = m_oldx;

it would cause this problem.

tlayton
Arrrggghhh...you are correct. I had set both of these to reference another array, each referencing the same. I clearly need to revise my Java reference logic! Thanks very much, I'd probably have been at this all night otherwise.
Peter
While you probably meant it correct, there's a lot to object to in your answer: Java has no pointers but references and naming them pointers might be confusing and might even let others think that you can do pointer-arithmetic with them. Also, Java has but one way to pass (instances of) objects: by value (the reference is copied by value!), calling it "passing by pointer", is misleading (or even wrong).
Bart Kiers
You are of course correct. I used some bad terminology in my answer. It has been corrected accordingly.
tlayton
@tlayton, cheers!
Bart Kiers