Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassign `this` in Java class

I'm just fooling around in Java right now, trying to implement something similar to a stack using linked lists.

class ListStack {

    int value;
    int size;
    ListStack next;

    public ListStack (int add) {
        this.size = 1;
        this.value = add;
        this.next = null;
    }

    public void push (int add) {
        this.next = this;
        this.value = add;
        this.size++;
    }

    public int pop() {
        if (this.size == 0) { throw new EmptyListStackException(); }
        int i = this.value;
        this = this.next;
        this.size--;
        return i;
    }

    public int size() {
        return this.size;
    }

    public int peek() {
        return this.value;
    }
}

Basically it's an insertion-in-front linked list which also removes from front. NetBeans pops an error when I try to do this = this.next; it says I cannot reassign final value this.

I'd like my final implementation to do something like the below:

ListStack var = new ListStack(5); //var is now 5 -> null
var.push(3); //var is now 3 -> 5 -> null
int val = varr.pop(); //var is now 5 -> null, val == 3

Commenting put that this = this.next code, the rest seems to work.

ListStack a = new ListStack(5);
System.out.println(a.size()); //prints 1
System.out.println(a.peek()); //prints 5
a.push(4);
System.out.println(a.size()); //prints 2
System.out.println(a.peek()); //prints 4
a.push(6);
System.out.println(a.size()); //prints 3
System.out.println(a.peek()); //prints 6
a.push(1);
System.out.println(a.size()); //prints 4
System.out.println(a.peek()); //prints 1
//a is 1 -> 6 -> 4 -> 5 -> null
like image 642
gator Avatar asked Mar 19 '23 21:03

gator


1 Answers

There is a conceptual error in your code: basically you are not creating any new stack element with your push method.

But the problem is that calling the class listStack becomes misleading, because actually what you want to create are new elements of the stack, so you should create a class node maybe. Moreover you can't ovveride "this" because it is a java keyword and it always refers to the current object.

To give you a hint of what to do to implement a stack as a linked list you should create class Node with a value field value and a reference to the previous Node (the first node will just have a null pointer) .

In the class ListStackyou should have a reference to the last node and its push() method should create a new Node and set this one as the new last node.

like image 85
merosss Avatar answered Mar 28 '23 03:03

merosss