Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Objects, unsure how this works.

 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have an array of Cube objects:

I also have a method which swaps the positions of some of the Cube's
in the array


So this code works, but I'm not sure why:
Since 'temp' refers to cubes[a], then when we set
cubes[a] to cubes[b], shouldn't temp then reference cubes[b].

It doesn't seem to, temp is set cubes[a], then it appears to be fixed, even when we change the value of cubes[a],

Can anyone clarify this.
Thanks
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Remember that cubes[a] and cubes[b] are just references.

In this code,



you can read this as

1. Make temp point to the object that cubes[a] is pointing to.
2. Make cubes[a] point to the object that cubes[b] is pointing to.
3. Make cubes[b] point to the object that cubes[c] is pointing to.
4. Make cubes[c] point to the object that cubes[d] is pointing to.
5. Make cubes[d] point to the object that temp is pointing to.

So in line 1, you would have

temp, cubes[a] ===> object 1
cubes[b] ===> object 2

In line 2, you would have

temp ===> object 1
cubes[a], cubes[b] ===> object 2
 
fred rosenberger
lowercase baba
Bartender
Posts: 12147
31
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an array of Cube objects


No, you really don't. you have an array of REFERENCES to cube objects. the cubes live off somewhere in the heap. your array holds (effectivly) a bunch of pointers to those objects.

Think of the array as a bunch of index cards, each having someones home address written on it.

when you say
Cube temp=cubes[a];

you are writting the address that is on cubes[a] on a new index card called 'temp'.

cubes[a] = cubes[b]

simply erases the old address on that card, and writes the new address on it. the contents of the house never change. the address written on your 'temp' card doesn't change.
 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent, both great explanations, that clears it up.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic