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?
We have:
Object head = listHead.datum;
listHead = listHead.next;
return head;
There are a number of references at play here:
listHead is a referencehead is a referencelistHead.datum is a referencelistHead.next is a referenceThere are two actual object instances being referenced:
datum references (let's call that instance D)next references (let's call that instance N)Here's how things go down.
listHead.datum has a reference to DlistHead.next has a reference to Nhead is given a reference to DN (note that head is not changed)head which still references DIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With