help with temporay variables

A

aDeamon

When I do this
char[][] board;
// here I have some code placing data into board

// later I do this in another method that takes the former board as a
input
char[][] tmpBoard = board;
for(Point p : HashSet<Point>) {
tmpBoard[p.x][p.y] = EMPTY;
}


For some reson both board AND tmpBoard has been changed and looks the
same. I would expect only tmpBoard to have changed - am I wrong?

/Sam
 
L

Lew

aDeamon said:
When I do this
char[][] board;
// here I have some code placing data into board

// later I do this in another method that takes the former board as a
input
char[][] tmpBoard = board;
for(Point p : HashSet<Point>) {
tmpBoard[p.x][p.y] = EMPTY;
}


For some reson both board AND tmpBoard has been changed and looks the
same. I would expect only tmpBoard to have changed - am I wrong?

Yes. Variables in Java (except primitives like int) are pointers to objects,
not objects themselves. tmpBoard and board both point to the same array;
you're not changing "tmpBoard", you're changing the object to which "tmpBoard"
points, which is the same as the object to which "board" points.

board --->{array in memory}
tmpBoard ---^
 
I

Ian Shef

When I do this
char[][] board;
// here I have some code placing data into board

// later I do this in another method that takes the former board as a
input
char[][] tmpBoard = board;
for(Point p : HashSet<Point>) {
tmpBoard[p.x][p.y] = EMPTY;
}


For some reson both board AND tmpBoard has been changed and looks the
same. I would expect only tmpBoard to have changed - am I wrong?

/Sam

I don't see any other replies to this one, so I will take a shot at it.
You are wrong.

The line
tmpBoard = board
does NOT copy the contents of an array from one place to another.
'board' references (points to) an array, and now 'tmpBoard' references
(points to) the SAME array. Changes to one are changes to the other because
there is NO other, they reference the same thing.

You need to allocate an array for 'tmpBoard' and use loops to copy from
'board' to 'tmpBoard'. You could also use java.lang.System.arraycopy(...)
but it may not help much because your arrays have multiple dimensions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,170
Latest member
Andrew1609
Top