下面这个程序的输出结果为:
2
3
为什么不是下面这个呢,望高手解答
3
3
public class Test { int i=2;
public static void main(String[] args){
Test t1=new Test();
t1.change(t1, 8);
System.out.println(t1.i); // 3
}
void change(Test t1,int i){
// i=5;
t1.i=3;
Test t2=new Test();
t1=t2;
System.out.println(t1.i); // 2
}
}
2
3
为什么不是下面这个呢,望高手解答
3
3
public class Test { int i=2;
public static void main(String[] args){
Test t1=new Test();
t1.change(t1, 8);
System.out.println(t1.i); // 3
}
void change(Test t1,int i){
// i=5;
t1.i=3;
Test t2=new Test();
t1=t2;
System.out.println(t1.i); // 2
}
}
t1引用了t2所有t1.i=3没用了.
打出的当然是t2.i了.
// i=5;
t1.i=3;
Test t2=new Test();
t1=t2;
System.out.println(t1.i); // 2
}
这个方法默认的对象参数传递方法是按址的,所以传进来的t1是上边定义的t1的地址,t1.i=3;这一句改变的是上面t1的值,然后在change这个作用域里的t1又被赋上了另一test对象的地址,现在它和t2同时指向在change作用域内new的对象,它的值显然是2.
所以输出结果为。3,2.
3
3只要t2=t1;
不是t1=t2;
t1.i = 3; //自身的i被改变,所以这里开始i==3;
Test t2 = new Test();
t1=t2; //这里开始,t1指向了另一个对象,不再==this
System.out.println(t1.i); //2
}
所以当然输出是
2
3
改成t1.i = t2.i;
在跑次。然后对照前面的答案 你就能看出为什么了。
public static void main(String[] args){
Test t1=new Test();
t1.change(t1, 8);
System.out.println(t1.i); //
}
void change(Test t1,int i){
// i=5;
//t1.i=3; ////////////////
Test t2=new Test();
t1=t2;
t1.i=3; ////////////
System.out.println(t1.i); //
}
}//我把这个位置调去那个位置.现在明了吧.
表示将t2的引用赋给t1的
然后t1指向了t2的属性了 输出的是t2的i
t1引用了t2所有t1.i=3没用了.
打出的当然是t2.i了.
你把t1=t2;
改成t1.i = t2.i;
在跑一次。然后对照前面的答案 你就能看出为什么了。