今天在做SCJP在线测试的时候,遇到这样一个问题:
1. public class Foo {
2. public static void main (String [] args) {
3. StringBuffer a = new StringBuffer (“A”);
4. StringBuffer b = new StringBuffer (“B”);
5. operate (a,b);
6. system.out.printIn{a + “,” +b};
7. )
8. static void operate (StringBuffer x, StringBuffer y) {
9. x.append {y};
10. y = x;
11. )
12. }
What is the result?
A The code compiles and prints “A,B”.
B The code compiles and prints “A,A”.
C The code compiles and prints “B,B”.
D The code compiles and prints “AB,B”.
E The code compiles and prints “AB,AB”.
F The code does not compile because “+” cannot be overloaded for StringBuffer. 给的答案是D,我总觉得应该选E
x.append {y}; 这一句到底又是什么意思?
1. public class Foo {
2. public static void main (String [] args) {
3. StringBuffer a = new StringBuffer (“A”);
4. StringBuffer b = new StringBuffer (“B”);
5. operate (a,b);
6. system.out.printIn{a + “,” +b};
7. )
8. static void operate (StringBuffer x, StringBuffer y) {
9. x.append {y};
10. y = x;
11. )
12. }
What is the result?
A The code compiles and prints “A,B”.
B The code compiles and prints “A,A”.
C The code compiles and prints “B,B”.
D The code compiles and prints “AB,B”.
E The code compiles and prints “AB,AB”.
F The code does not compile because “+” cannot be overloaded for StringBuffer. 给的答案是D,我总觉得应该选E
x.append {y}; 这一句到底又是什么意思?
String不可变,StringBuffer可变
方法执行之后,String没有改变,而StringBuffer在原来的基础上增加了一点内容
StringBuffer a = new StringBuffer ("A");
StringBuffer b = new StringBuffer ("B");
a和b都是StringBuffer,都会改变自己里面的内容。为什么最后b的值没变呢?
因为调用了operator方法。引用本身按值传递,但是可以改变对象的状态,y = x;这句话并不会改变b的指向对象,所以b所指向的对象并不是a指向的对象,而是它自己指向的对象!所以b指向的对象的内容不会变
答案应该是B
因为y = x;对于对象b来说是不起作用的他并没有改变b的引用
输出应该是AB,B
x.append (y);
y = x;
}
这样问题出现这这个方法里面,operate (a,b);这个其实传递的是一个复制后的引用,就是说它复制了a和b给了x和y,然后方法里面的x指向跟a同一个引用(A),y指向跟b一样的引用(B),然后x通过append方法改变了x指向的对象A,改变成AB(注意:因为你的a和y指向同一个对象,所以当你打印a的值时,是改变后的值)。然后就是把y的引用指向跟x一样的引用,本来x指向的是AB,所以y指向的也是AB,但是这个并没有改变b引用的指向,它还是指向B,这是因为y和b的无关导致的,y只是b的复制品!试试改成这样,你跟踪变化情况,你就会知道,他们究竟在干了什么!
public static void main (String [] args) {
StringBuffer a = new StringBuffer ("A");
System.out.println(a);
StringBuffer b = new StringBuffer ("B");
System.out.println(b);
operate (a,b);
System.out.println(a + "," +b);
}
static void operate (StringBuffer x, StringBuffer y) {
x.append (y);
System.out.println(x);
y=x;
System.out.println(y);
}
b,y 指向同一对象
x.append(y) 使 a引用的StringBuffer对象的内容是 "AB"
y=x 改变了y的指向(和x引用同一对象),但是实际参数b不受影响,其引用的对象的内容还是"B"