面试中碰到一个题
public class Example
{
String str = new String("good");
char[] ch = { 'a', 'b', 'c' };
public static void main(String[] args) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.print(ex.str + "and");
System.out.print(ex.ch);
}
public void change(String str, char ch[]) {
str = "test ok";
ch[0] = 'g';
}
}
根据映像 回来上网查到 然后运行 结果输入good and gbc 和我预想的不同
觉得原因是 string源码里写的 Multiple strings can share the same char[] because strings are immutable
String是不可变的
请教了大神得知 change()方法里面 str 的引用只是指向了 "test ok" 这个字符串
并没有改变"good"这个字符串
就是说 :
字符串 "good"是一个不变的字符串 ;
change()里面的str是另一个复制的字符串
当执行change(String str )方法的时候 在change内部重新创建了"text ok字符串"
然后改变了 str的指向 并且只能在change方法内可用 并没有改变原有的"good"字符串
所以输出了 good and gbc
如果我总结的不对 希望大神指出一下
祝大家编程每日精进