除了存放位置不同外,这两者有什么区别?
String test="aaa";是否等同于String test=new String("aaa");
除了存放位置不同外,这两者有什么区别?
String test="aaa";是否等同于String test=new String("aaa");
不一样,第一个只创建了一个对象,第二个创建了两个对象
下面是String构造函数,可以看到,它把"aaaa"复制了一份到自己的缓冲里
public String(String original) {
this.count = original.count;
if (original.value.length > this.count) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
this.value = new char[this.count];
System.arraycopy(original.value, original.offset,
this.value, 0, this.count);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
this.value = original.value;
}
}
还是不相信我说的?看看楼上说的。
有区别的
String test="aaa";这个test是一个string类型的值
String test=new String("aaa");这个test 是一个string的对象