Java:对象分配

fui*_*iii 2 java reference object

我在java中,当你这样做时object1=object2,你会复制object2to 的引用object1,所以object1object2指向"同一个对象.是不是?

我写了一个函数来排序堆栈.

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()+" ");
        //}
    }
}
Run Code Online (Sandbox Code Playgroud)

我无法从班级得到任何输出.如果我取消注释打印部分,它说的很好.我s调用函数后,我不明白堆栈是空的.我已经分配dst给了s,所以s应该指向dst堆栈,对吧?

请帮忙!谢谢!

Hov*_*els 9

您正在为参数src分配一个参数,该参数实际上是一个局部变量,因此您没有看到对原始Stack变量s的任何影响.而是让方法返回dst并分配返回的对象.即

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

   return dst;
}
Run Code Online (Sandbox Code Playgroud)

s = sortStack(s);
Run Code Online (Sandbox Code Playgroud)


Jef*_*ica 6

设置时,src=dst您只覆盖方法中的引用的本地副本.在调用方法的过程中,本地副本由每个参数组成,这样在您的方法中通过其方法修改src会在方法之外产生影响,但是将src分配给像dst这样的新引用则不会.

如果您return dst进入sortStacks = sortStack(s)调用您的调用函数,您的代码将会起作用.