Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array being modified in a line of code that doesn't mention it

 
Rick Gentry
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


spotStatusWithCurrent and spotStatus are both int[][]. Somehow, someway, spotStatus is being modified in the line I marked. Is there some little known pointer system in java? Have I been hallucinating for days and this isn't really happening? Have demons infested my computer after playing just a bit too much doom? But seriously, someone please help, I'm going crazy trying to figure out how this is possible.
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays are objects. When you say

Object a = Object b;

they are both pointers to the same object. There is indeed a pointer system, although I'd question just how little-known it is. you have set both pointers to reference the same array. Change that array, both pointers still point to the modified object. I suggest just using a for loop to copy the array, but if you like methods with lots of parameters that you could just have easily written yourself, there's System.arraycopy. Oh, methods that don't follow conventions, tack that on too.
 
Warren Dew
blacksmith
Ranch Hand
Posts: 1332
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays in Java are kind of like objects; array variables are references. When you do the line:

spotStatusWithCurrent = spotStatus

both spotStatusWithCurrent and spotStatus both refer to the same array. Modifications through either reference modify the same array, and are thus visible through the other reference as well.

Perhaps you meant to copy the array, rather than just assign a new reference to it?
 
Rick Gentry
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you thank you thank you

Why would anyone want two references to the same set of variables?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12202
35
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would anyone want two references to the same set of variables?

That's what happens when you pass an object as a parameter into a method. If i have:


while i am in my method(), i have a second reference to the same array. changes made to the array will be seen once i leave the method.

not that if i change the REFERENCE in the method:

the original array is not changed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic