String str = new String("abc")創建了幾個對象?結合源碼解析
首先,我們看一下jdk源碼:
1 /** 2 * Initializes a newly created {@code String} object so that it represents 3 * the same sequence of characters as the argument; in other words, the 4 * newly created string is a copy of the argument string. Unless an 5 * explicit copy of {@code original} is needed, use of this constructor is 6 * unnecessary since Strings are immutable. 7 * 8 * @param original 9 * A {@code String} 10 */ 11 public String(String original) { 12 this.value = original.value; 13 this.hash = original.hash; 14 }
大家都知道String本身就是個引用類型,我們可以將String str = new String("adc")分為四部分來看,String str 第一部分變量名,=為第二部分給str賦值使用的,new String()為第三部分創建對象,"abc"為第三部分對象內容,然而第一部分和第二部分並沒有創建對象。第三部分new String()肯定是創建了對象的。那么另一個對象時從何來的呢?從上面的源碼中我們會看到一個帶參的String的構造器;如果方法區的常量池里面沒有所傳的參數對象,這個參數會在方法區的常量池里面創建一個,加上我們new出來的,會有兩個對象;但是如果在方法區里面有該參數,那么就會直接獲取,因此jvm只會在堆里面創建對象本身,棧里面引用地址,這個時候就只有一個對象存在。所以,至於有多少個對象被創建,這個主要看之前是不是String original參數傳入,要是情況而定。
如有錯誤請多多指出。
