jQuery in Action, 3rd edition
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 OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Objects, unsure how this works." Watch "Objects, unsure how this works." New topic

Objects, unsure how this works.

colin shuker
Ranch Hand

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

Joined: Oct 02, 2003
Posts: 11880

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: 750
Excellent, both great explanations, that clears it up.
I agree. Here's the link: http://aspose.com/file-tools
subject: Objects, unsure how this works.
It's not a secret anymore!