I am new to java.
The question might not be that clear. Let me explain using code.
The code below is a function that prints out values in a linkedlist.
The first line of the function creates a reference to point to the same object that is pointed by the HeadNode reference. So any changes to currentNode will affect the object that HeadNode is pointing to.
Now, inside the while loop, I am making the change of the currentNode, but I observe the linkedList didn’t change after I exit the function. Why?
static void PrintLinkedList(ListNode HeadNode)
{
ListNode currentNode = HeadNode;
while(currentNode != null)
{
System.out.println(currentNode.getData());
currentNode = currentNode.getNext();
}
}
UPDATE:
the reason of me bring this quesiton up is that when I implemented a function to reverse a linkedlist, my tempNode become null after the following code executed:
static ListNode ReverseLinkedList(ListNode headNode)
{
ListNode headNodeTemp = headNode;
headNodeTemp.setNext(null);
ListNode tempNode = headNode.getNext(); //temp becomes null because headNode is changed. Why??
ListNode currentNode = headNodeTemp;
while(tempNode != null)
{...
No,
currentNodeis a reference to the objectHeadNodealso refers to. You never change that object, all you change is whatcurrentNoderefers to.makes
currentNodepoint to the next object, it doesn’t change any object.To change the object, you need to call a method or set a property,
would change the pointed-to object, and these changes would be visible when the object is queried through
HeadNode.just makes
currentNodepoint to another object.In
here, we call a method that changes the pointed-to object. Going by the name, it sets the
nextfield tonull. And the objectheadNodeTemppoints to is the objectheadNodepoints to.You should move the
line above the
setNext(null)line.