Java中String和Array作爲函數參數的區別

String類應該是封裝的char數組,但它只提供了char charAt(int)方法來獲得指定位置的字符,而沒有相應的setter方法來設置特定位置的字符,所以String對象一旦初始化,其內容不可變更。String類中String concat(String)方法就是返回了一個新的String對象的引用。

 

  1. package htgy; 
  2.  
  3. import java.util.Arrays; 
  4.  
  5. public class ReferenceDemo { 
  6.  
  7.     /** 
  8.      * @param args 
  9.      */ 
  10.     public static void main(String[] args) { 
  11.         String s = "abc"
  12.         System.out.println("1:" + s); 
  13.          
  14.         f(s); 
  15.         System.out.println("2:" + s); 
  16.          
  17.         s = g(s); 
  18.         System.out.println("3:" + s); 
  19.          
  20.         // 因爲String不可變,所以要編輯字符串的內容,採用String g(String) 的方式。 
  21.          
  22.         int[] a = {123}; 
  23.         System.out.println("4:" + Arrays.toString(a)); 
  24.          
  25.         f1(a); 
  26.         System.out.println("5:" + Arrays.toString(a)); 
  27.          
  28.         f(a); 
  29.         System.out.println("6:" + Arrays.toString(a)); 
  30.          
  31.         a = g(a); 
  32.         System.out.println("7:" + Arrays.toString(a)); 
  33.          
  34.         // void f(int[]) 和 int[] g(int[])的效果相同。 
  35.         // 要改變數組的內容,一般採用 f(int[]) 的方式。 
  36.          
  37.  
  38.     } 
  39.      
  40.     static void f(String s) { 
  41.         s = s + "123";  // String內容不可改變,s指向了另一個String對象 
  42.         System.out.println("方法void f(String)中:" + s); 
  43.     } 
  44.      
  45.     static String g(String s) { 
  46.         s += "123"// String內容不可改變,s指向了另一個String對象 
  47.         System.out.println("方法String g(String)中:" + s); 
  48.         return s;   // 將新對象的引用返回 
  49.     } 
  50.      
  51.     static void f(int[] a) { 
  52.         a[1] = 7;   // 數組內容可以改變 
  53.         System.out.println("方法void f(int[])中:" + Arrays.toString(a)); 
  54.     } 
  55.      
  56.     static int[] g(int[] a) { 
  57.         a[1] = 7;   // 數組內容可以改變 
  58.         System.out.println("方法int[] g(int[])中:" + Arrays.toString(a)); 
  59.         return a;   // 返回原對象的引用 
  60.     } 
  61.      
  62.     static void f1(int[] a) { 
  63.         a = new int[]{456}; // a指向了另一個數組對象 
  64.         System.out.println("方法void f1(int[])中:" + Arrays.toString(a)); 
  65.     }    
  66.  
  67. //~ Output: 
  68. /* 
  69.  * 1:abc 
  70.  * 方法void f(String)中:abc123 
  71.  * 2:abc 
  72.  * 方法String g(String)中:abc123 
  73.  * 3:abc123 
  74.  * 4:[1, 2, 3] 
  75.  * 方法void f1(int[])中:[4, 5, 6] 
  76.  * 5:[1, 2, 3] 
  77.  * 方法void f(int[])中:[1, 7, 3] 
  78.  * 6:[1, 7, 3] 
  79.  * 方法int[] g(int[])中:[1, 7, 3] 
  80.  * 7:[1, 7, 3] 
  81.  */ 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章