[Java] Java is Pass by Value and Not Pass by Reference

Java到底是pass by value還是pass by reference?說法眾說紛紜,後來看到這篇文章Java is Pass by Value and Not Pass by Reference後,觀念才整個釐清。

Java是pass by value!

範例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class Balloon {

private String color;

public Balloon() {
}

public Balloon(String c) {
this.color = c;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}

public static void main(String[] args) {
Balloon red = new Balloon("Red");
Balloon blue = new Balloon("Blue");

swap(red, blue);
System.out.println("red color=" + red.getColor());
System.out.println("blue color=" + blue.getColor());

foo(blue);
System.out.println("blue color=" + blue.getColor());

}

private static void foo(Balloon balloon) {
balloon.setColor("Red");
balloon = new Balloon("Green");
balloon.setColor("Blue");
}

public static void swap(Object o1, Object o2) {
Object temp = o1;
o1 = o2;
o2 = temp;
}

public static void swap1(Balloon o1, Balloon o2) {
String temp = o1.getColor();
o1.setColor(o2.getColor());
o2.setColor(temp);
}
}

結果:

1
2
3
4
5
6
7
8
9
//使用swap()
red color=Red
blue color=Blue
blue color=Red

//使用swap1()
red color=Blue
blue color=Red
blue color=Red

分析:

  1. 尚未執行swap():
  2. 執行swap(),o1指向red,o2指向blue:
  3. swap()執行結束,原本的物件並沒有互相交換:
  4. 執行foo(),ballon指向blue:
  5. 執行foo()第一行,透過原本物件的setter method修改值:
  6. 執行foo()第二行:
  7. 執行foo()第三行:

因為Java是採用pass by value作法,當以物件作為參數傳入到method,在method裡面想要修改物件的值,需透過物件的setter method,這樣原本物件的值才會連帶一起變更。透過assign(=)或new等方式,原本物件的值都不會有變化。

參考資料: