java编程,函数内变量传递问题,为什么没有都改变呢?
阿神
阿神 2017-04-18 10:51:11
0
3
611

代码如下:

public void test(BSTNode<T> z)
    {
        BSTNode<T> y;
        if (z.left != null){
            y = z.parent;
            BSTNode<T> a;
            a = y.left;
            if (y != null){
                System.out.println("before a             "+a);
                System.out.println("before y.left        "+y.left);
                System.out.println("befere z.parent.left "+z.parent.left);
                y.left = null;
                //a = null;
                System.out.println("after a              "+a);
                System.out.println("after y.left         "+y.left);
                System.out.println("after z.parent.left  "+z.parent.left);
            }
        }
    }

打印结果如下:
before a threadSleep.BSTree$BSTNode@15db9742
before y.left threadSleep.BSTree$BSTNode@15db9742
befere z.parent.left threadSleep.BSTree$BSTNode@15db9742
after a threadSleep.BSTree$BSTNode@15db9742
after y.left null
after z.parent.left null

请问 “after a ”为什么不是null?

或者将代码:

y.left = null;

            //a = null;

改为

//y.left = null;

a = null;

结果为:

before a threadSleep.BSTree$BSTNode@15db9742

before y.left threadSleep.BSTree$BSTNode@15db9742

befere z.parent.left threadSleep.BSTree$BSTNode@15db9742

after a threadSleep.BSTree$BSTNode@15db9742

after y.left null

after z.parent.left null

运行环境:

jdk1.8

阿神
阿神

闭关修行中......

reply all(3)
大家讲道理

Your results will definitely be different twice. In fact, it is the same as the one below.


int x = 10;
int y = x;
y = 0;
x ?
刘奇

Passing by reference in Java is essentially passing the address of the object. The address is actually passed by value. Through this address, the value of the object pointed to in the memory can be modified. Changing the value of this address makes no sense except losing control of the real object.

左手右手慢动作

I’m coming, I’m coming

It’s very simple. You only need to understand that passing by reference transfers an address. After this address is passed, it will be placed in the local variable of the called method. There are two stack frames for the two methods, and each stack frame has its own local variable tables, do not affect each other. So this is why you pass a reference and then change the reference point to have no image of the original one.

So, why does the value of val change when obj.val is modified? Because the value of val is stored in the heap. It is copied, modified, and then written back to the heap, so it changes. If you don’t understand, you can continue to ask questions

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template