I have a linked list using objects of class “ListNode”
ListNode has the following non static methods:
getValue()
setValue(Object obj)
getNext()
setNext(ListNode ln)
It’s constructor takes a value and a next.
In my main method in my driver class, create my linked list:
ListNode head = new ListNode("Overflow!", null);
head = new ListNode("Stack", head);
head = new ListNode("in", head);
head = new ListNode("is", head);
head = new ListNode("This", head);
I have a method called printList(ListNode ln).
I call it twice consecutively in my main method like this:
printList(head);
System.out.println();
printList(head);
My method looks like this:
public static void printList(ListNode head)
{
while(head != null)
{
System.out.print(head.getValue()+" ");
head = head.getNext();
}
}
In my method, the reference is changed to point to a different object each time in the while loop. So after I exit the method, the reference “head” should be pointing to a null, right? However, when the printList(head) is called the second time, it magically prints all the elements in the list!
Here is what the jGrasp console shows:
----jGRASP exec: java StackOverflowQuestionExampleClass
This is in Stack Overflow!
This is in Stack Overflow!
----jGRASP: operation complete.
Here is the listnode class my teacher told me to use:
//Thomas Bettge, TJHSST, 10-20-2006
public class ListNode
{
private Object value;
private ListNode next;
public ListNode(Object v, ListNode n)
{
value=v;
next=n;
}
public Object getValue()
{
return value;
}
public ListNode getNext()
{
return next;
}
public void setValue(Object newv)
{
value=newv;
}
public void setNext(ListNode newn)
{
next=newn;
}
}
Confusion is probably stemming from the fact that you have 2 labels with the same name “head”. The “head” argument in the printList method is a new reference to the object that was passed in. reassigning it doesn’t affect the target of the original reference (in the sense that t won’t cause it to reference something else. an aside: changes to the state of the referenced object will have an effect, as it’s the same object, regardless of what is referencing it).
might make it clearer to look at your code like this: