简体   繁体   中英

Passing params to methods in Java

I am confused with one trivial thing - passing parameters to the method and changing their values... I'll better give you some code:

public class Test {
  public static void main(String[] args) {
    Integer val = new Integer(41);
    upd(val);
    System.out.println(val);

    Man man = new Man();
    updMan(man);
    System.out.println(man.name);
  }

  static void upd(Integer val) {
    val = new Integer(42);
  }

  static void updMan(Man man) {
    man.name = "Name";
  }

  static class Man {
    String name;
  }
}

Could you explain why the Integer object I've passed is not updated while the Man object is? Aren't the Integer and Man objects passed by reference (due to their non-primitive nature)?

Because for Integer your are creating a new Object. For Man you just change one of its value, the object man stays the same.

Consider the following:

static void updMan(Man man) {
  man = new Man();
  man.name = "Another Man";
}

This would also not change your initial man .

--EDIT

You can "simulate" the mutability of Integer by this:

static void upd(Integer val) {
    try {
        Field declaredField = val.getClass().getDeclaredField("value");
        declaredField.setAccessible(true);
        declaredField.set(val, 42);
    } catch (Exception e) {
    }
}

It is called Pass by value . When you pass some object to dome method, Java creates a copy of reference to that object. If you check object's hashcode right after going into method's body it will be the same as passed object's one. But when you change it inside of method, object changes and reference is no longer points to same object.

EDIT : code sample

public class TestPass {

    public static void main(String[] args) {
        String ss= "sample";
        System.out.println("Outside method: "+ss.hashCode());
        method(ss);

    }

    static void method(String s){
        System.out.println("Inside method: "+s.hashCode());
        s+='!';
        System.out.println("Inside method after object change: "+s.hashCode());
    }

}

Output:

Outside method: -909675094
Inside method: -909675094
Inside method after change: 1864843191

objects as parameters in Java are transferred as a params by copy of reference - so if you change the object via reference copy - you will have your object updated.

in case of your upd(Integer val) method you create a new Integer object so that reference copy now point to a new object, not the old one. So changing that object will not affect the original one.

man.name = "Name"; 

实际上,您正在更改同一对象中的某些内容,而不是像在整数情况下那样创建新对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM