Link to home
Start Free TrialLog in
Avatar of manish_London
manish_London

asked on

"this" in Java

I'm playing around with a personally implemented Linked List stack.  I am reversing the order of the stack structure i'm holding (which is just a list of connected Linked nodes)

For some reason I can't assign "this" to a another object of the same type.  i.e. can't do,

this = tempStack;

Probably silly, but why is that?
Avatar of Ashish Patel
Ashish Patel
Flag of India image

this is static to self object and cannot be reassinged
"this" is a reserved keyword that refers to the object on which the current constructor/method is operating.  Perhaps this code can clarify:

class Person {

    String name;

    Person(String s) {
        this.name = s;
        // "this" refers to the new instance created by this constructor
    }

    void greet(Person p) {
        System.out.println("Hi" + p.name + ".  My name is " + this.name + ".");
        // "this" refers to the object on which this method is called.
    }
}

Elsewhere...

Person jack = new Person("Jack");
Person jill = new Person("Jill");
jack.greet(jill); //prints "Hi Jill.  My name is Jack."

When you call jack.greet(...), the "this" in the greet method refers to the Person jack.
Avatar of agsuvidha
agsuvidha

Do
this.tempstackt=tempstack

You can never assign a value to "this."  It's not a variable; it's a keyword which acts like a variable.  The only way to change the current object is to modify its fields, much like agsuvidha suggests.

Do you mind posting your source code?
Avatar of manish_London

ASKER

The following method does the job but not the nicest way I think.  I'm going to produce a recursive solutionn next.      
                      /**
       * returns a reversed version of this stack, iterative solution
       */
      public LinkedStack reverseMe (){
            //note assignment does not appear to work with this
            LinkedStack tempStack = new LinkedStack();
            LinkedStack tempStack2 = new LinkedStack();
            
            while (!this.isEmpty()){
                  tempStack.push(this.pop());
            }
            
            while (!tempStack.isEmpty()){
                  tempStack2.push(tempStack.pop());
            }            
            
            //now push back into this, in the correct order
            while (!tempStack2.isEmpty()){
                  this.push(tempStack2.pop());
            }            
            
            return this;
      }
ASKER CERTIFIED SOLUTION
Avatar of malfunction84
malfunction84
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial