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 s = "asdf"; 其实建了string,s和"asdf"
不好意思,剛才說錯了 應該是 String s = new String("asdf"); 是直接產生一個新的實例 String s = "asdf"; 是先到堆中尋找是否有"asdf"這個對象,如果有,則讓s指向他,如果沒有,則產生一個新的實例 public class test { public static void main(String args[]){ String t1="ab"; String t2="ab"; //new String("abc"); String t3=new String("abc"); String t4="abc"; System.out.println(t1); System.out.println(t2); System.out.println(t3); if (t1==t2) System.out.println("=="); else System.out.println("!="); } } 這裡可以看出t1和t2的地址是相同的
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,s和"asdf"
應該是
String s = new String("asdf");
是直接產生一個新的實例
String s = "asdf";
是先到堆中尋找是否有"asdf"這個對象,如果有,則讓s指向他,如果沒有,則產生一個新的實例
public class test
{
public static void main(String args[]){
String t1="ab";
String t2="ab"; //new String("abc");
String t3=new String("abc");
String t4="abc";
System.out.println(t1);
System.out.println(t2);
System.out.println(t3);
if (t1==t2)
System.out.println("==");
else
System.out.println("!=");
}
}
這裡可以看出t1和t2的地址是相同的