开发者

Puzzling behaviour (Java instances, arrays & GWT)

开发者 https://www.devze.com 2023-01-04 07:44 出处:网络
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 instanc

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[开发者_JAVA技巧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 :(


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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消