Java题目分析
赋值问题
String 和 Char 赋值问题
如题
- 判断下列代码输出情况
public class Example {
String str = new String("good");
char[] ch = { 'a', 'b', 'c' };
public void change(String str, char ch[]) {
str = "test ok";
ch[0] = 'g';
}
public static void main(String[] args) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.println(ex.str);
for(char a : ex.ch)
System.out.print(a + " ");
}
}
输出结果为
good
g,b,c
原因
? Java中 String 类型是 immutable (不可变得),即 引用指向内容 不可变
? 也就是说定义一个 String 类型 变量 str ,给 str 赋予初值 "aa",再给 str 赋值 "bb",str 赋值 "bb" 时,不是改变 "aa"的存储内容,而是 重新开辟一块存储空间,同时原先指向 "aa"地址不可达了,jvm 通过 GC自动回收。
? 题中 方法调用时,str = "test ok" 语句开辟了新的地址,但是原来的 str 仍然 指向 "good",所以输出时仍然是 good ,数组中 参数 ch 指向了类中 ch 指向的数组,语句改变了 类中的数组内容。
public class Example {
String str = new String("good");
char[] ch = { 'a', 'b', 'c' };
public void change(String str, char ch[]) {
str = "test ok";
System.out.println("形参str 哈希码 :" + str.hashCode());
ch[0] = 'g';
}
public static void main(String[] args) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.println("成员变量str 哈希码 :" + ex.str.hashCode());
System.out.println(ex.str);
for(char a : ex.ch)
System.out.print(a + " ");
}
}
通过 查看哈希码 能发现他们地址不同 :
解决方法
方法一
- 不使用形参输入,直接调用成员变量 str
public class Example {
String str = new String("good");
char[] ch = { 'a', 'b', 'c' };
public void change(char ch[]) {
str = "test ok";
ch[0] = 'g';
}
public static void main(String[] args) {
Example ex = new Example();
ex.change(ex.ch);
System.out.println(ex.str);
for(char a : ex.ch)
System.out.print(a + " ");
}
}
方法二
- 使用 this 调用 成员变量
public class Example {
String str = new String("good");
char[] ch = { 'a', 'b', 'c' };
public void change(String str, char ch[]) {
this.str = "test ok";
ch[0] = 'g';
}
public static void main(String[] args) {
Example ex = new Example();
ex.change(ex.str, ex.ch);
System.out.println(ex.str);
for(char a : ex.ch)
System.out.print(a + " ");
}
}
方法三
- 将 str 以返回值的方式 用对象 调用 成员变量 str
public class Example {
String str = new String("good");
char[] ch = { 'a', 'b', 'c' };
public String change(String str,char ch[]) {
str = "test ok";
ch[0] = 'g';
return str;
}
public static void main(String[] args) {
Example ex = new Example();
ex.change(ex.str,ex.ch);
System.out.println(ex.change(ex.str,ex.ch));
for(char a : ex.ch)
System.out.print(a + " ");
}
}
参考于:https://blog.csdn.net/weixin_30765505/article/details/95110037