fuiiii
fuiiii

Reputation: 1369

Java: object assign

I though in java, when you do object1=object2, you will copy the reference of object2 to object1, so object1 and object2 point" to the same object. Is it right?

I wrote a function to sort a stack.

import java.util.Stack;

public class sortStack {

    public static void main(String[] str) {
        Stack<Integer> s = new Stack<Integer>();
        s.push(2);
        s.push(21);
        s.push(43);
        s.push(3);
        s.push(87);
        s.push(2);
        s.push(12);
        s.push(10);
        s.push(25);
        sortStack(s);

        while (!s.isEmpty()) {
            System.out.print(s.pop() + " ");
        }
    }

    public static void sortStack(Stack<Integer> src) {
        Stack<Integer> dst = new Stack<Integer>();
        Stack<Integer> buf = new Stack<Integer>();//buffer

        while (!src.isEmpty()) {
            int v = src.pop();
            if (dst.isEmpty()) {
                dst.push(v);
            }

            while (!dst.isEmpty() && dst.peek() > v) {
                buf.push(dst.pop());
            }

            dst.push(v);
            while (!buf.isEmpty()) {
                dst.push(buf.pop());
            }
        }
        src = dst;

        //Print:
        //while(!src.isEmpty()){
        //  System.out.print(src.pop()+" ");
        //}
    }
}

I couldn't get any output from the class. If I uncomment the print part, it words fine. I don't understand the s stack is empty after I call the function. I already assign dst to s, so s should point to the dst stack, right?

Please help! Thanks!

Upvotes: 2

Views: 742

Answers (2)

Jeff Bowman
Jeff Bowman

Reputation: 95764

When you set src=dst you are only overwriting the local copy of the reference within the method. In the process of calling the method local copies are made of each parameter, such that within your method modifying src through its methods would have an effect outside the method but assigning src to a new reference like dst would not.

Your code will work if you return dst in sortStack and put s = sortStack(s) in your calling function.

Upvotes: 6

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285440

You are assigning a reference to a parameter, src, which is in fact a local variable, and hence you're not seeing any effect on the original Stack variable, s. Instead have the method return dst and assign the object returned. i.e.,

public static Stack<Integer> sortStack(Stack<Integer> src) {
    // ....

   return dst;
}

and

s = sortStack(s);

Upvotes: 9

Related Questions