This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Objects, unsure how this works. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Objects, unsure how this works." Watch "Objects, unsure how this works." New topic
Author

Objects, unsure how this works.

colin shuker
Ranch Hand

Joined: Apr 11, 2005
Posts: 743
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

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Oct 02, 2003
Posts: 10925
    
  12

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
colin shuker
Ranch Hand

Joined: Apr 11, 2005
Posts: 743
Excellent, both great explanations, that clears it up.
 
jQuery in Action, 2nd edition
 
subject: Objects, unsure how this works.
 
Similar Threads
Sorting question
Gaunt's moan of the week :)
How do i get all subsets?
Can someone tell me why?
Bert Bates Kathy Sierra Java 6 Study Guide