昨晚遇到了關於方法中傳遞的問題,然后牽扯上了Integer,當時難以理解,后來查了一些資料,終於搞懂了。
附上方便理解的代碼:
1 import java.lang.String; 2 public class Test { 3 public static void main(String[] args) { 4 int[] a = { 1, 2 }; 5 // 調用swap(int,int) 典型的值傳遞 6 swap(a[0], a[1]); 7 System.out.println("swap(int,int):a[0]=" + a[0] + ", a[1]=" + a[1]); //輸出為swap(int,int):a[0]=1, a[1]=2 8 9 // --------------------------------------------------- 10 // 引用傳遞,直接傳遞頭指針的引用。改變就是改變相應地址上的值 11 swap(a, 1); 12 System.out .println("swap(int [],int):a[0]=" + a[0] + ", a[1]=" + a[1]); //輸出為 swap(int [],int):a[0]=2, a[1]=1 13 // ---------------------------------------------------- 14 Integer x0 = new Integer(a[0]); 15 Integer x1 = new Integer(a[1]); 16 // 調用swap(Integer,Integer) 17 swap(x0, x1); 18 System.out.println("swap(Integer,Integer):x0=" + x0 + ", x1=" + x1); //輸出為 swap(Integer,Integer):x0=2, x1=1 19 // ----------------------------------------------------- 20 // intValue和valueof的區別和聯系 21 // intvalue返回的是int值,而 valueof 返回的是Integer的對象,它們的調用方式也不同 22 int x = x0.intValue(); 23 Integer s = Integer.valueOf(x0); 24 /* 25 * x == s輸 出為true 這里面涉及到一個自動打包解包的過程,如果jdk版本過低的話沒有這個功能的,所以輸出的是false 26 * 現在新版本的jdk都有自動打包解包功能了 27 */ 28 System.out.println("compare:int=" + x + ", Integer=" + s + " "+ (x == s)); //輸出為 compare:int=2, Integer=2 true 29 // ----------------------------------------------------- 30 StringBuffer sA = new StringBuffer("A"); 31 StringBuffer sB = new StringBuffer("B"); 32 System.out.println("Original:sA=" + sA + ", sB=" + sB); //輸出為 Original:sA=A, sB=B 33 append(sA, sB); 33 System.out.println("Afterappend:sA=" + sA + ", sB=" + sB); //輸出為 Afterappend:sA=AB, sB=B 34 } 35 public static void swap(int n1, int n2) { 36 int tmp = n1; 37 n1 = n2; 38 n2 = tmp; 39 } 40 public static void swap(int a[], int n) { 41 int tmp = a[0]; 42 a[0] = a[1]; 43 a[1] = tmp; 44 } 45 // Integer 是按引用傳遞的,但是Integer 類沒有用於可以修改引用所指向值的方法,不像StringBuffer 46 public static void swap(Integer n1, Integer n2) { // 傳遞的是a 的引用,但引用本身是按值傳遞的 47 Integer tmp = n1; 48 n1 = n2; 49 n2 = tmp; 50 } 51 // StringBuffer和Integer一樣是類,同樣在方法中是引用傳遞,但是StringBuffer類有用於可以修改引用所指向值的方法,如.append 52 public static void append(StringBuffer n1, StringBuffer n2) { 53 n1.append(n2); 54 n2 = n1; 55 } 56 }