原文出處:海子
相信String這個類是Java中使用得最頻繁的類之一,並且又是各大公司面試喜歡問到的地方,今天就來和大家一起學習一下String、StringBuilder和StringBuffer這幾個類,分析它們的異同點以及瞭解各個類適用的場景。下面是本文的目錄大綱:
一.你瞭解String類嗎?
二.深入理解String、StringBuffer、StringBuilder
三.不同場景下三個類的性能測試
四.常見的關於String、StringBuffer的面試題(闢謠網上流傳的一些曲解String類的說法)
若有不正之處,請多多諒解和指正,不勝感激。
一.你瞭解String類嗎?
想要了解一個類,最好的辦法就是看這個類的實現源代碼,String類的實現在
\jdk1.6.0_14\src\java\lang\String.java 文件中。
打開這個類文件就會發現String類是被final修飾的:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
{
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
/** Cache the hash code for the string */
private int hash; // Default to 0
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;
......
}
從上面可以看出幾點:
1)String類是final類,也即意味着String類不能被繼承,並且它的成員方法都默認爲final方法。在Java中,被final修飾的類是不允許被繼承的,並且該類中的成員方法都默認爲final方法。在早期的JVM實現版本中,被final修飾的方法會被轉爲內嵌調用以提升執行效率。而從Java SE5/6開始,就漸漸擯棄這種方式了。因此在現在的Java SE版本中,不需要考慮用final去提升方法調用效率。只有在確定不想讓該方法被覆蓋時,纔將方法設置爲final。
2)上面列舉出了String類中所有的成員屬性,從上面可以看出String類其實是通過char數組來保存字符串的。
下面再繼續看String類的一些方法實現:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}
public String replace(char oldChar, char newChar) {
if (oldChar != newChar) {
int len = count;
int i = -1;
char[] val = value; /* avoid getfield opcode */
int off = offset; /* avoid getfield opcode */
while (++i < len) {
if (val[off + i] == oldChar) {
break;
}
}
if (i < len) {
char buf[] = new char[len];
for (int j = 0 ; j < i ; j++) {
buf[j] = val[off+j];
}
while (i < len) {
char c = val[off + i];
buf[i] = (c == oldChar) ? newChar : c;
i++;
}
return new String(0, len, buf);
}
}
return this;
從上面的三個方法可以看出,無論是sub操、concat還是replace操作都不是在原有的字符串上進行的,而是重新生成了一個新的字符串對象。也就是說進行這些操作後,最原始的字符串並沒有被改變。
在這裏要永遠記住一點:
“對String對象的任何改變都不影響到原對象,相關的任何change操作都會生成新的對象”。
在瞭解了於String類基礎的知識後,下面來看一些在平常使用中容易忽略和混淆的地方。
二.深入理解String、StringBuffer、StringBuilder
1.String str=”hello world”和String str=new String(“hello world”)的區別
想必大家對上面2個語句都不陌生,在平時寫代碼的過程中也經常遇到,那麼它們到底有什麼區別和聯繫呢?下面先看幾個例子:
public class Main {
public static void main(String[] args) {
String str1 = "hello world";
String str2 = new String("hello world");
String str3 = "hello world";
String str4 = new String("hello world");
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str2==str4);
}
}
這段代碼的輸出結果爲:
爲什麼會出現這樣的結果?下面解釋一下原因:
在前面一篇講解關於JVM內存機制的一篇博文中提到 ,在class文件中有一部分 來存儲編譯期間生成的 字面常量以及符號引用,這部分叫做class文件常量池,在運行期間對應着方法區的運行時常量池。
因此在上述代碼中,String str1 = “hello world”;和String str3 = “hello world”; 都在編譯期間生成了 字面常量和符號引用,運行期間字面常量”hello world”被存儲在運行時常量池(當然只保存了一份)。通過這種方式來將String對象跟引用綁定的話,JVM執行引擎會先在運行時常量池查找是否存在相同的字面常量,如果存在,則直接將引用指向已經存在的字面常量;否則在運行時常量池開闢一個空間來存儲該字面常量,並將引用指向該字面常量。
總所周知,通過new關鍵字來生成對象是在堆區進行的,而在堆區進行對象生成的過程是不會去檢測該對象是否已經存在的。因此通過new來創建對象,創建出的一定是不同的對象,即使字符串的內容是相同的。
2.String、StringBuffer以及StringBuilder的區別
既然在Java中已經存在了String類,那爲什麼還需要StringBuilder和StringBuffer類呢?
那麼看下面這段代碼:
public class Main {
public static void main(String[] args) {
String string = "";
for(int i=0;i<10000;i++){
string += "hello";
}
}
}
這句 string += “hello”;的過程相當於將原有的string變量指向的對象內容取出與”hello”作字符串相加操作再存進另一個新的String對象當中,再讓string變量指向新生成的對象。如果大家還有疑問可以反編譯其字節碼文件便清楚了:
<圖略>
從這段反編譯出的字節碼文件可以很清楚地看出:從第8行開始到第35行是整個循環的執行過程,並且每次循環會new出一個StringBuilder對象,然後進行append操作,最後通過toString方法返回String對象。也就是說這個循環執行完畢new出了10000個對象,試想一下,如果這些對象沒有被回收,會造成多大的內存資源浪費。從上面還可以看出:string+=”hello”的操作事實上會自動被JVM優化成:
StringBuilder str = new StringBuilder(string);
str.append(“hello”);
str.toString();
未完待續。。。