Java - 这似乎是通过引用传递给我的

Sha*_*awn 4 java

可能重复:
Java是否通过引用传递?

因此,请考虑以下两个示例及其各自的输出:

public class LooksLikePassByValue {

    public static void main(String[] args) {

        Integer num = 1;
        change(num);
        System.out.println(num);
    }

    public static void change(Integer num)
    {
        num = 2;
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

1


  public class LooksLikePassByReference {

    public static void main(String[] args) {

        Properties properties = new Properties();
        properties.setProperty("url", "www.google.com");
        change(properties);
        System.out.println(properties.getProperty("url"));
    }

    public static void change(Properties properties2)
    {
        properties2.setProperty("url", "www.yahoo.com");
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

www.yahoo.com

为什么会这样www.yahoo.com?对我来说看起来不像passbyvalue.

Pet*_*hev 10

所述参考是按值传递.但新引用仍指向同一原始对象.所以你修改它.在您的第一个示例中,Integer您正在更改引用所指向的对象.所以原来没有修改.