Reputation: 943
Code from CCI book:
public class ListNode {
int val;
ListNode next = null;
ListNode(int x) {
this.val = x;
}
And this:
public void appendToTail(int d) {
ListNode end = new ListNode(d);
ListNode n = this;
while (n.next != null) {
n = n.next;
}
n.next = end;
}
Original: 5 -> 10 -> 15
As I understand, in this case "n" and "this" refer to same object yet, after debugging and stepping through:
"n" becomes 15 -> 20
"this" becomes 5 -> 10 -> 15 -> 20
How can this be? When I change "n", "this" should change as well?
So everything I did on "n" ,BESIDES appending 20, did not reflect on "this".
UPDATE:
Anyone who has same question should read this.
Upvotes: 2
Views: 1214
Reputation: 9373
From the Java Language Specification:
[…] the keyword
this
denotes a value that is a reference to the object for which the instance method or default method was invoked […]
You only invoke appendToTail(int)
on one particular node of your list, so this
always refers to the same object. If you want to "step into" each node during debugging, you could change the implementation as follows:
public void appendToTail(int d) {
if (next != null) {
next.appendToTail(d);
} else {
next = new ListNode(d);
}
}
Upvotes: 0
Reputation: 2792
Inside your while loop you say:
n = n.next
When that line of code executes you change the value of n from "this" to n.next. This points to the current link object in the list and next points to a completely different object. As you walk your way through the linked list the value of n keeps updating as you pass through each link in the linked list.
When you get to the end of the linked list there is no next, i.e. value of n is null. So you exit the while loop and add a new link to the end of the linked list.
Upvotes: 1