Tai M. Tai M. - 1 year ago 77
Java Question

What does "this" refer to in Linked List example?

So I'm skimming through Cracking the Coding Interview to brush up on some interview stuff and I ran across this linked list implementation, and maybe it's been a while but it's completely going over my head. I understand most of it, except for one specific line, and it's throwing me off. I'll post the code below (for reference, the book doesn't mention language but it appears to be Java.)

class Node {
Node next = null;
int data;

public Node(int d) {
data = d;

void appendToTail(int d) {
Node end = new Node(d);
Node n = this;
while(n.next != null) {
n = n.next;
n.next = end;

I'm a little confused on the line:
Node n = this
- I'm not sure what
is referring to, unless it's talking about
- why not just set it to
in that case?

Answer Source

this refers to a specific instance of an object of a class. Since objects are constructed there can be multiple instances of a class, but using the this keyword allows you to obtain a reference to itself, meaning a reference to the the specific instance of the object whose method is being called.

The linked list is a collection of nodes that are, well, linked together. When you call appendToTail() the node will look at all of the Node objects linked to itself and follow the chain. For it to get a reference to itself to follow its own chain the this keyword is used.

You also ask why null isn't used in this case to initialize n. This would cause a NullPointerException when n.next is first called in the loop constraint, so instead its own reference is used as the starting point for the iteration of the linked-list.

This (pun intended) can be a confusing topic at first, but lets use the example you provided.

Node n = this;
while(n.next != null) {
    n = n.next;

Let's pretend that there are 4 objects currently linked in our list and for simplicity's sake the Node object that appendToTail() is being called on is the head of the list. Here's the reference value of Node n that's held on each loop iteration from the above snippet.

  1. We're pointing to ourself - this
  2. Pointing to the second item in the linked list. - this.next
  3. Pointing to the following item - this.next.next
  4. Pointing to the last item in the list - this.next.next.next

The loop ended so currently the reference of n = this.next.next.next. We then set n's next value (where n is currently pointing to the end of the linked chain) to the new object we created at the beginning of our method, which makes it the new end of the list. (n.next = end is now equivalent to this.next.next.next.next = end).

Semi-Unnecessary Edit: This is explained in terms of Java. It appears that someone added the C++ tag after I wrote this answer