Question

I am confused about how object references work and was wondering if someone could help. Below is some example code which is supposed to deQueue a Queue based on a linked list for the general case:

Object head = listHead.datum;
listHead = listHead.next;
return head;

My understanding is that when you have a primitive variable the actual value is stored is assigned to it, but if the variable is an object then a reference to an object is stored in there. So in the above code a reference to listHead.datum is stored in head, but then the reference stored in listHead is changed to be listHead.next. When it comes time to return the Object called head I would have thought that it would follow it's assigned reference i.e. go to listHead (which now refers to a different place) and then to datum.

The above code should return the head of the Queue but following my logic it will return the second in the queue. Where am I going wrong?

Was it helpful?

Solution

We have:

Object head = listHead.datum;
listHead = listHead.next;
return head;

There are a number of references at play here:

  • listHead is a reference
  • head is a reference
  • listHead.datum is a reference
  • listHead.next is a reference

There are two actual object instances being referenced:

  • whatever datum references (let's call that instance D)
  • whatever next references (let's call that instance N)

Here's how things go down.

  • listHead.datum has a reference to D
  • listHead.next has a reference to N
  • head is given a reference to D
  • listHead is given a reference to N (note that head is not changed)
  • you return head which still references D

OTHER TIPS

The head reference isn't updated dynamically as listHead changes. In fact, no object reference has dynamic resolution. The reference has to be explicitly changed through direct assignment. This is the only way to achieve what you thought was happening:

Object head = listHead.datum;
listHead = listHead.next;
// Only direct assignment can change the object that head points to
head = listHead.datum;
return head;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top