Why can't my Java method change a passed variable?

This question already has an answer here:

  • Is Java “pass-by-reference” or “pass-by-value”? 79 answers

  • References to objects are passed by value in Java so assigning to the local variable inside the method doesn't change the original variable. Only the local variable s points to a new string. It might be easier to understand with a little ASCII art.

    Initially you have this:

    ------------
    | nullTest |
    ------------
         |
        null
    

    When you first enter the method setNotNull you get a copy of the value of nullTest in s . In this case the value of nullTest is a null reference:

    ------------    ------------
    | nullTest |    |    s     |
    ------------    ------------
         |               |
        null            null
    

    Then reassign s:

    ------------    ------------
    | nullTest |    |    s     |
    ------------    ------------
         |               |
        null         "not null!"
    

    And then leave the method:

    ------------
    | nullTest |
    ------------
         |
        null
    

    Java doesnt pass by reference, it passes the value of the reference. When you are assigning s="not null" , you are reassigning that value.


    I was hoping to do something like setNotNull(MyObject o) without using o = setNotNull(o)

    Simply, you cannot. The closest you will get is something like this:

    public class MyRef<T> {
        private T obj;
    
        public T get() {
            return obj;
        }
    
        public void set(T obj) {
            this.obj = obj;
        }
    
        public void setNotNull(T obj) {
            if (this.obj == null) {
                this.obj = obj;
            }
        }
    }
    
    MyRef<MyObj> ref = new MyRef<MyObj>();
    ref.setNotNull(xyz);
    System.err.println(ref.get());
    

    which is all rather clunky, and probably not worth the effort.

    链接地址: http://www.djcxy.com/p/86698.html

    上一篇: Java按值传递和按引用传递

    下一篇: 为什么我的Java方法不能更改传递的变量?