对象作参数传递后改变对象的属性,返回变化后的结果,是值传递?还是引用传递?

是值传递。

Java 语言的方法调用只支持参数的值传递。

当一个对象实例作为一 个参数被传递到方法中时,参数的值就是对该对象的引用。对象的属性可以在被调用过程中被改变,但对对象引用的改变是不会影响到调用者的。


代码:

@Test
public void demo() {
    JSONObject jsonObject = new JSONObject();

    jsonObject.putOpt("name", "andrew");

    System.out.println(jsonObject.hashCode());
    // 打印内存地址
    System.out.println(System.identityHashCode(jsonObject));

    jsonObject = show(jsonObject);

    System.out.println();
    System.out.println(jsonObject.hashCode());
    System.out.println(System.identityHashCode(jsonObject));
}

private JSONObject print(JSONObject jsonObject) {
    jsonObject.putOpt("name", "歪瓜仁");
    System.out.println();
    System.out.println(jsonObject.hashCode());
    System.out.println(System.identityHashCode(jsonObject));

    return jsonObject;
}

结果:

-1410326011
1481818223

26399971
1481818223

26399971
1481818223


版权声明:本文为xhaimail原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。