我认为: 首先Vector里存放的是引用,s也是引用 v1.add(s)的作用是在v1中插入一个引用,这个引用指向“this is a String”(注意:不是指向s) 在执行s = new String("this is a new String")后,s已指向"this is a new String",而Vector中的两个引用仍然指向“this is a String” 输出当然是两个“this is a String”了
还是那句话 ,String 是比较特殊的 无论你是s = new String("this is a new String"); 或者是 s="this is a new String";打印的结果应该还是 this is a String this is a String
不好意思,上述说法不太准确,应该是这样理解 String tmp1 = new String("this is a String"); s=tmp1; v1.add(s); v1.add(s); 相当于保存tmp1;
String tmp2 = new String("this is a new String"); s=tmp2; v1 中的引用还是tmp1,没有改变。
import java.util.*;public class test { public static void main(String[] argv)throws Exception{ Vector v=new Vector(); A a=new A(); v.add(a);//=99 a.a=100; A a2=(A)v.get(0); System.out.println(a2.a);//=100 } } class A{ public int a=99; } ////////////////////////////////////////////// 而s = new String("this is a new String");或s="this is a new String"; 都是把 s指向了新的内容,不影响vetor.
了解??!!!
而原来的对象引用只存在Vector中,所以会出现这种情况,如果是StringBuffer对象则
会与楼住想象的结果一样
首先Vector里存放的是引用,s也是引用
v1.add(s)的作用是在v1中插入一个引用,这个引用指向“this is a String”(注意:不是指向s)
在执行s = new String("this is a new String")后,s已指向"this is a new String",而Vector中的两个引用仍然指向“this is a String”
输出当然是两个“this is a String”了
无论你是s = new String("this is a new String");
或者是 s="this is a new String";打印的结果应该还是
this is a String
this is a String
String tmp1 = new String("this is a String");
s=tmp1;
v1.add(s);
v1.add(s); 相当于保存tmp1;
String tmp2 = new String("this is a new String");
s=tmp2;
v1 中的引用还是tmp1,没有改变。
import java.util.*;public class test {
public static void main(String[] argv)throws Exception{
Vector v=new Vector();
A a=new A();
v.add(a);//=99
a.a=100;
A a2=(A)v.get(0);
System.out.println(a2.a);//=100
}
}
class A{
public int a=99;
}
//////////////////////////////////////////////
而s = new String("this is a new String");或s="this is a new String";
都是把 s指向了新的内容,不影响vetor.
}
}
class A{
public int a=99;
}
liudongbaollz()
zealVampire(蚊子+鹤舞白沙)
我认同以上三位的解释,尤其是jxc1999() 我觉得就是标准答案了:)