今天朋友问我关于char数组为什么不是“good and abc”

来源:互联网 发布:阿里云虚拟主机这么用 编辑:程序博客网 时间:2024/05/01 08:38
今天看了一道题,代码如下:
[java] view plaincopyprint?
  1. public class Example{   
  2.   String str=new String("good");   
  3.   char[]ch={'a','b','c'};   
  4.   public static void main(String args[]){   
  5.     Example ex=new Example();   
  6.     ex.change(ex.str,ex.ch);   
  7.     System.out.print(ex.str+" and ");   
  8.     Sytem.out.print(ex.ch);   
  9.   }   
  10.   public void change(String str,char ch[]){   
  11.     str="test ok";   
  12.     ch[0]='g';   
  13.   }   
  14. }   

其结果是 good and gbc ,为啥 string 没改变而char 改变了呢??

原来是因为:

str是按值传递,所以在函数中对它的操作只生效于它的副本,与原字符串无关。
ch是按址传递,在函数中根据地址,可以直接对字符串进行操作。

str指向的是String类的引用,保存的是地址。当新的“test good ”产生的时候,会在内存中新建String对象,将地址复制给changes方法的str。而ch不会产生新的char数组,直接对原来的数组进行更改。


然后,当原来的程序改下后:

[java] view plaincopyprint?
  1. public class StringArrTest {  
  2.     String str = new String("good");  
  3.     char[] ch = { 'a''b''c' };  
  4.     int[] arr = new int[] { 123 };  
  5.   
  6.     public static void main(String[] args) {  
  7.         StringArrTest ex = new StringArrTest();  
  8.         ex.changes(ex.str, ex.ch, ex.arr);  
  9.         System.out.print(ex.str + "  and  ");  
  10.         System.out.print(ex.ch);  
  11.         System.out.print(ex.arr[0]);  
  12.         // System.out.println(ex.arr);  
  13.     }  
  14.   
  15.     public void changes(String str, char ch[], int[] arr) {  
  16.         str = "test ok";  
  17.         System.out.println("chagne str:" + str);  
  18.         ch[0] = 'g';  
  19.         System.out.print("change ch :");  
  20.         System.out.println(ch);  
  21.         arr[0] = 4;  
  22.         System.out.print("change arr :");  
  23.         System.out.println(arr[0]);  
  24.     }  
  25. }  

打印的结果:

可以看到,输出字符数组和整形数组是不一样的,字符数组会把所有字符输出来,那是因为System.out.print(a);此方法会自动给你解析你的数组,然后打印出来的。而当是整形数组的时候,就会打印出该数组的地址(当然是首地址)。

如果在将 

System.out.print(ex.str + "  and  " +ex.ch);

ch也会打印出字符数组的地址,而不会解析数组,依次打印每个字符了。

0 0
原创粉丝点击