先使用int實驗:
1
2
3
4
5
6
7
8
9
10
11
12
|
public class ttest { private static list<userentity> mlist = new linkedlist<userentity>(); public static void main(string[] args) { int a = 0 ; changea(a); system.out.println( "a = " +a); } public static void changea( int a){ a = 1 ; } } |
輸出:a = 0
這說明對于int值是按值傳遞。其他幾個基本類型也是如此。
再使用自己定義的類userentity來實驗:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class userentity { private string name; public string getname() { return name; } public void setname(string name) { this .name = name; } } public class ttest { public static void main(string[] args) { userentity userentity = new userentity(); userentity.setname( "猿猴" ); changename(userentity); system.out.println( "name = " +userentity.getname()); } public static void changename(userentity userentity){ userentity.setname( "忽必烈" ); } } |
輸出:name = 忽必烈
我們再來使用一個linkedlist<object>來實驗:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import java.util.linkedlist; import java.util.list; public class ttest { private static list<userentity> mlist = new linkedlist<userentity>(); public static void main(string[] args) { userentity userentity = new userentity(); userentity.setname( "石頭" ); adduser(userentity); system.out.println( "name = " +userentity.getname()); } public static void adduser(userentity userentity){ mlist.add(userentity); mlist.get( 0 ).setname( "猿猴" ); } } |
輸出:name= 猿猴
這說明在使用我們自己定義的類時,是按引用傳遞的。
接著,再來使用string實驗:
1
2
3
4
5
6
7
8
9
10
|
public class ttest { public static void main(string[] args) { string str= "開始的" ; changestr(str); system.out.println( "str = " +str); } public static void changestr(string str){ str = "改變的" ; } } |
輸出:str = 開始的
用integer做實驗也會發現沒有改變。
說明我們按照java內置的對象也是值傳遞。因此我們可以做如下總結:
只要我們自己定義的類創建的對象,都是引用傳遞,系統內置的基本類型和對象都是指傳遞。
總結
以上所述是小編給大家介紹的java中的按值傳遞和按引用傳遞,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://blog.csdn.net/qq_34939308/article/details/80674829