public class AboutStr {
String str=new String("good");
char[] ch={'a','b','c'};
public static void main(String[] args) {
AboutStr ex=new AboutStr();
ex.change(ex.str,ex.ch);
System.out.print(ex.str+" and ");
System.out.println(ex.ch);
}
public void change(String str,char[] ch1){
str="text ok";
ch1[0]='g';
}}为什么输出结果是 good and gbc 呢?菜鸟
String str=new String("good");
char[] ch={'a','b','c'};
public static void main(String[] args) {
AboutStr ex=new AboutStr();
ex.change(ex.str,ex.ch);
System.out.print(ex.str+" and ");
System.out.println(ex.ch);
}
public void change(String str,char[] ch1){
str="text ok";
ch1[0]='g';
}}为什么输出结果是 good and gbc 呢?菜鸟
public void change(String str,char[] ch1){
str="text ok";
ch1[0]='g';
}
这里面的这个str的值变了,但是这里只是传值,而不是传对象,所以仅仅只是在这个方法里面str的值为"text ok",而在主函数中,str的值并没有变。
你改成这样就可以了。
public void change(String str,char[] ch1){
this.str="text ok";
this.ch1[0]='g';
}
我主要不明白的是,为什么ex.ch的值变了?
public static void main(String[] args) throws IOException {
char[]test = {'a','b','c'};
exchange(test);
System.out.println(test);
}
private static void exchange(char[] test){
test = null;
}
如果它直接修改自己本身,对源对象不会有丝毫影响,但是他内部的属性修改是可以直接影响到的,比如A和B都指向地址C,A修改自己本身其实修改了自己指向的地址,可是他们共同指向C的属性是可以相互影响的,这就牵扯到深拷贝和浅拷贝了。
ex.ch变了就好比A和B都指向C,然后A改变了C的具体值,所以导致B的具体值也发生了变化。
而 ch1=null 就好比把A指向另外一个地址,所以不影响B的值。
是这么理解的么?
你可以在编辑框上面一排看看,可以调整格式,各种语言的格式都可以设置