總結:
1.將對象(對象的引用)作為參數傳遞時傳遞的是引用(相當于指針)。也就是說函數內對參數所做的修改會影響原來的對象。
2.當將基本類型或基本類型的包裝集作為參數傳遞時,傳遞的是值。也就是說函數內對參數所做的修改不會影響原來的變量。
3.數組(數組引用))作為參數傳遞時傳遞的是引用(相當于指針)。也就是說函數內對參數所做的修改會影響原來的數組。
4.String類型(引用)作為參數傳遞時傳遞的是引用,只是對String做出任何修改時有一個新的String對象會產生,原來的String對象的值不會做任何修改。(但是可以將新的對象的 引用賦給原來的引用,這樣給人的表面現象就是原來的對象變了,其實沒有變,只是原來指向它的引用指向了新的對象)。
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
package StringTest; class A{ int a= 1 ; char b= 'A' ; public A(){} public A( int _a, char _b){ this .a=_a; this .b=_b; } public String toString(){ return "a=" + this .a+ ",b=" + this .b; } } public class ReferenceTest { public static A changeA(A classa){ classa.a= 2 ; classa.b= 'B' ; return classa; } public static String changeString(String str){ System.out.println(str.hashCode()); str=str.toLowerCase(); System.out.println(str.hashCode()); return str; } public static int changeint( int a){ a=a+ 1 ; return a; } public static Integer changeInteger(Integer a){ a= new Integer( 9 ); return a; } public static int [] changeintarray( int a[]){ a[ 0 ]= 10 ; return a; } public static void printArray( int a[]){ for ( int i= 0 ;i<a.length;i++){ System.out.print(a[i]+ " " ); } System.out.println(); } public static void main(String[] args) { //自定義的對象傳遞的是引用 A a= new A(); A b=changeA(a); System.out.println(a); System.out.println(b); System.out.println( "----------------------" ); //String對象作為參數傳遞的也是引用(只是String對象的值不能變,每一個修改String對象的值都會重新創建一個新的String對象用以保存修改后的值,原來的值不會變) String str1= "HUHUALIANG" ; System.out.println(str1.hashCode()); String str2=changeString(str1); System.out.println(str2.hashCode()); System.out.println(str1); System.out.println(str2); System.out.println( "----------------------" ); //基本類型是值傳遞 int inta= 8 ; int intb=changeint(inta); System.out.println(inta); System.out.println(intb); System.out.println( "----------------------" ); //基本類型的包裝集作為參數傳遞的是值而不是引用 Integer c= new Integer( 1 ); Integer d=changeInteger(c); System.out.println(c); System.out.println(d); System.out.println( "----------------------" ); //數組傳遞的是引用 int [] arraya={ 0 , 1 , 2 , 3 }; int [] arrayb=changeintarray(arraya); printArray(arraya); printArray(arrayb); } } |
運行結果:
a=2,b=B
a=2,b=B
----------------------
711139030
711139030
226046678
226046678
HUHUALIANG
huhualiang
----------------------
8
9
----------------------
1
9
----------------------
10 1 2 3
10 1 2 3
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!