Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about how object references work in Java

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?

like image 956
user1058210 Avatar asked Dec 03 '25 17:12

user1058210


1 Answers

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
like image 168
Marvo Avatar answered Dec 06 '25 06:12

Marvo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!