0

I'm new at learning Java and I wanted to try my luck with linked lists. It all worked perfectly, but now I want to replace all direct calls to attributes of the nodes with get and set methods. There is however one method that troubles me. I wanted to implement a setNode method that would set the current node as another node.

Here is some of the relevant code:

public class ListNode {
    
    int value;
    ListNode next;

    // more code exists in-between but it shouldn't be related (theoretically speaking :P)
    
    public void setNode(ListNode node) {
        this = node;
    }

}

When I try to compile the program, I get the following error message:

ListNode.java:32: error: cannot assign a value to final variable this
                this = node;
                ^

So I was wondering if there is some sort of a workaround, and also why we can do this without issues:

node = node.next;
// or
node = node2;

for example, but not this:

this = this.next;
// or
this = node2;
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

0

The 'this' keyword represents the current object you're referencing. So you simply can't assign an object value to 'this'.

Am suggesting the following changes to your code,

public void setValue(int value) {
    this.value = value;
}

public void setNextNode(ListNode node) {
    this.next = node;
}

  • 1
    Thanks for the reply! I probably got confused because I thought that if node is a ListNode and node2 is also a ListNode then I could assign node as node2 because they were the same type. Good to know you can't do it like that! So using both setValue and setNextNode would have the desired result? –  May 04 '20 at 07:22
  • setValue() will help you in assigning a value to that node. setNextNode() will assign the next pointer of the node to a new node. In a linked list you'll set the next pointer to another node for all nodes and the last node in the list will have its next pointer pointed to null. – Karthick Ramachandran May 04 '20 at 07:34
0

this keyword is used to refer current object in java. More importantly, your error gives the information that this is a final variable (hence it cannot be changed). The reason it is made the final variable is that it can be used anytime to get the context of current object. Imagine if someone modifies it, how can it be used later in the code where the current object is required.

In your example, you need to use the following:

public void setNode(ListNode node) {
     this.next = node;
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jitesh Shivnani
  • 363
  • 1
  • 9