探祕Java中的String、StringBuilder以及StringBuffer

探祕Java中String、StringBuilder以及StringBufferhtml

  相信String這個類是Java中使用得最頻繁的類之一,而且又是各大公司面試喜歡問到的地方,今天就來和你們一塊兒學習一下String、StringBuilder和StringBuffer這幾個類,分析它們的異同點以及瞭解各個類適用的場景。下面是本文的目錄大綱:java

  一.你瞭解String類嗎?程序員

  二.深刻理解String、StringBuffer、StringBuilderweb

  三.不一樣場景下三個類的性能測試面試

  四.常見的關於String、StringBuffer的面試題(闢謠網上流傳的一些曲解String類的說法)數組

  如有不正之處,請多多諒解和指正,不勝感激。安全

  請尊重做者勞動成果,轉載請標明轉載地址:多線程

   http://www.cnblogs.com/dolphin0520/p/3778589.htmlapp

一.你瞭解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();

  再看下面這段代碼:

public class Main {
		
	public static void main(String[] args) {
		StringBuilder stringBuilder = new StringBuilder();
		for(int i=0;i<10000;i++){
			stringBuilder.append("hello");
		}
	}
}

  反編譯字節碼文件獲得:

  

  從這裏能夠明顯看出,這段代碼的for循環式從13行開始到27行結束,而且new操做只進行了一次,也就是說只生成了一個對象,append操做是在原有對象的基礎上進行的。所以在循環了10000次以後,這段代碼所佔的資源要比上面小得多。

  那麼有人會問既然有了StringBuilder類,爲何還須要StringBuffer類?查看源代碼便一目瞭然,事實上,StringBuilder和StringBuffer類擁有的成員屬性以及成員方法基本相同,區別是StringBuffer類的成員方法前面多了一個關鍵字:synchronized,不用多說,這個關鍵字是在多線程訪問時起到安全保護做用的,也就是說StringBuffer是線程安全的。

  下面摘了2段代碼分別來自StringBuffer和StringBuilder,insert方法的具體實現:

  StringBuilder的insert方法

  public StringBuilder insert(int index, char str[], int offset,
                                int len) 
    {
        super.insert(index, str, offset, len);
	return this;
    }

  StringBuffer的insert方法:

public synchronized StringBuffer insert(int index, char str[], int offset,
                                            int len) 
    {
        super.insert(index, str, offset, len);
        return this;
    }

三.不一樣場景下三個類的性能測試

  從第二節咱們已經看出了三個類的區別,這一小節咱們來作個小測試,來測試一下三個類的性能區別:

public class Main {
	private static int time = 50000;
	public static void main(String[] args) {
		testString();
		testStringBuffer();
		testStringBuilder();
		test1String();
		test2String();
	}
	
	
	public static void testString () {
		String s="";
		long begin = System.currentTimeMillis(); 
		for(int i=0; i<time; i++){ 
			s += "java"; 
		} 
		long over = System.currentTimeMillis(); 
		System.out.println("操做"+s.getClass().getName()+"類型使用的時間爲:"+(over-begin)+"毫秒"); 
	}
	
	public static void testStringBuffer () {
		StringBuffer sb = new StringBuffer();
		long begin = System.currentTimeMillis(); 
		for(int i=0; i<time; i++){ 
			sb.append("java"); 
		} 
		long over = System.currentTimeMillis(); 
		System.out.println("操做"+sb.getClass().getName()+"類型使用的時間爲:"+(over-begin)+"毫秒"); 
	}
	
	public static void testStringBuilder () {
		StringBuilder sb = new StringBuilder();
		long begin = System.currentTimeMillis(); 
		for(int i=0; i<time; i++){ 
			sb.append("java"); 
		} 
		long over = System.currentTimeMillis(); 
		System.out.println("操做"+sb.getClass().getName()+"類型使用的時間爲:"+(over-begin)+"毫秒"); 
	}
	
	public static void test1String () {
		long begin = System.currentTimeMillis(); 
		for(int i=0; i<time; i++){ 
			String s = "I"+"love"+"java"; 
		} 
		long over = System.currentTimeMillis(); 
		System.out.println("字符串直接相加操做:"+(over-begin)+"毫秒"); 
	}
	
	public static void test2String () {
		String s1 ="I";
		String s2 = "love";
		String s3 = "java";
		long begin = System.currentTimeMillis(); 
		for(int i=0; i<time; i++){ 
			String s = s1+s2+s3; 
		} 
		long over = System.currentTimeMillis(); 
		System.out.println("字符串間接相加操做:"+(over-begin)+"毫秒"); 
	}
	
}

  測試結果(win7,Eclipse,JDK6):

  

  上面提到string+="hello"的操做事實上會自動被JVM優化,看下面這段代碼:

public class Main {
	private static int time = 50000;
	public static void main(String[] args) {
		testString();
		testOptimalString();
	}
	
	
	public static void testString () {
		String s="";
		long begin = System.currentTimeMillis(); 
		for(int i=0; i<time; i++){ 
			s += "java"; 
		} 
		long over = System.currentTimeMillis(); 
		System.out.println("操做"+s.getClass().getName()+"類型使用的時間爲:"+(over-begin)+"毫秒"); 
	}
	
	public static void testOptimalString () {
		String s="";
		long begin = System.currentTimeMillis(); 
		for(int i=0; i<time; i++){ 
			StringBuilder sb = new StringBuilder(s);
			sb.append("java");
			s=sb.toString();
		} 
		long over = System.currentTimeMillis(); 
		System.out.println("模擬JVM優化操做的時間爲:"+(over-begin)+"毫秒"); 
	}
	
}
	

  執行結果:

  

  獲得驗證。

  下面對上面的執行結果進行通常性的解釋:

  1)對於直接相加字符串,效率很高,由於在編譯器便肯定了它的值,也就是說形如"I"+"love"+"java"; 的字符串相加,在編譯期間便被優化成了"Ilovejava"。這個能夠用javap -c命令反編譯生成的class文件進行驗證。

  對於間接相加(即包含字符串引用),形如s1+s2+s3; 效率要比直接相加低,由於在編譯器不會對引用變量進行優化。

  2)String、StringBuilder、StringBuffer三者的執行效率:

  StringBuilder > StringBuffer > String

  固然這個是相對的,不必定在全部狀況下都是這樣。

  好比String str = "hello"+ "world"的效率就比 StringBuilder st  = new StringBuilder().append("hello").append("world")要高。

  所以,這三個類是各有利弊,應當根據不一樣的狀況來進行選擇使用:

  當字符串相加操做或者改動較少的狀況下,建議使用 String str="hello"這種形式;

  當字符串相加操做較多的狀況下,建議使用StringBuilder,若是採用了多線程,則使用StringBuffer。

 

四.常見的關於String、StringBuffer的面試題

  下面是一些常見的關於String、StringBuffer的一些面試筆試題,如有不正之處,請諒解和批評指正。

1. 下面這段代碼的輸出結果是什麼?

  String a = "hello2";   String b = "hello" + 2;   System.out.println((a == b));

  輸出結果爲:true。緣由很簡單,"hello"+2在編譯期間就已經被優化成"hello2",所以在運行期間,變量a和變量b指向的是同一個對象。

2.下面這段代碼的輸出結果是什麼?

  String a = "hello2";    String b = "hello";       String c = b + 2;       System.out.println((a == c));

  輸出結果爲:false。因爲有符號引用的存在,因此  String c = b + 2;不會在編譯期間被優化,不會把b+2當作字面常量來處理的,所以這種方式生成的對象事實上是保存在堆上的。所以a和c指向的並非同一個對象。javap -c獲得的內容:

  

3.下面這段代碼的輸出結果是什麼?

  String a = "hello2";     final String b = "hello";       String c = b + 2;       System.out.println((a == c));

  輸出結果爲:true。對於被final修飾的變量,會在class文件常量池中保存一個副本,也就是說不會經過鏈接而進行訪問,對final變量的訪問在編譯期間都會直接被替代爲真實的值。那麼String c = b + 2;在編譯期間就會被優化成:String c = "hello" + 2; 下圖是javap -c的內容:

  

4.下面這段代碼輸出結果爲:

public class Main {
	public static void main(String[] args) {
		String a = "hello2"; 
		final String b = getHello();
		String c = b + 2; 
		System.out.println((a == c));
	}
	
	public static String getHello() {
		return "hello";
	}
}

  輸出結果爲false。這裏面雖然將b用final修飾了,可是因爲其賦值是經過方法調用返回的,那麼它的值只能在運行期間肯定,所以a和c指向的不是同一個對象。

5.下面這段代碼的輸出結果是什麼?

public class Main {
	public static void main(String[] args) {
		String a = "hello";
		String b =  new String("hello");
		String c =  new String("hello");
		String d = b.intern();
		
		System.out.println(a==b);
		System.out.println(b==c);
		System.out.println(b==d);
		System.out.println(a==d);
	}
}

  輸出結果爲(JDK版本 JDK6):

  

  這裏面涉及到的是String.intern方法的使用。在String類中,intern方法是一個本地方法,在JAVA SE6以前,intern方法會在運行時常量池中查找是否存在內容相同的字符串,若是存在則返回指向該字符串的引用,若是不存在,則會將該字符串入池,並返回一個指向該字符串的引用。所以,a和d指向的是同一個對象。

6.String str = new String("abc")建立了多少個對象?

  這個問題在不少書籍上都有說到好比《Java程序員面試寶典》,包括不少國內大公司筆試面試題都會遇到,大部分網上流傳的以及一些面試書籍上都說是2個對象,這種說法是片面的。

  若是有不懂得地方能夠參考這篇帖子:

  http://rednaxelafx.iteye.com/blog/774673/

  首先必須弄清楚建立對象的含義,建立是何時建立的?這段代碼在運行期間會建立2個對象麼?毫無疑問不可能,用javap -c反編譯便可獲得JVM執行的字節碼內容:

  

  很顯然,new只調用了一次,也就是說只建立了一個對象。

  而這道題目讓人混淆的地方就是這裏,這段代碼在運行期間確實只建立了一個對象,即在堆上建立了"abc"對象。而爲何你們都在說是2個對象呢,這裏面要澄清一個概念  該段代碼執行過程和類的加載過程是有區別的。在類加載的過程當中,確實在運行時常量池中建立了一個"abc"對象,而在代碼執行過程當中確實只建立了一個String對象。

  所以,這個問題若是換成 String str = new String("abc")涉及到幾個String對象?合理的解釋是2個。

  我的以爲在面試的時候若是遇到這個問題,能夠向面試官詢問清楚」是這段代碼執行過程當中建立了多少個對象仍是涉及到多少個對象「再根據具體的來進行回答。

7.下面這段代碼1)和2)的區別是什麼?

public class Main {
	public static void main(String[] args) {
		String str1 = "I";
		//str1 += "love"+"java";        1)
		str1 = str1+"love"+"java";      //2)
		
	}
}

  1)的效率比2)的效率要高,1)中的"love"+"java"在編譯期間會被優化成"lovejava",而2)中的不會被優化。下面是兩種方式的字節碼:

  1)的字節碼:

  

  2)的字節碼:

  

  能夠看出,在1)中只進行了一次append操做,而在2)中進行了兩次append操做。

  參考文章:http://rednaxelafx.iteye.com/blog/774673/

       http://www.blogjava.net/Jack2007/archive/2008/06/17/208602.html

         http://www.jb51.net/article/36041.htm

       http://blog.csdn.net/yirentianran/article/details/2871417

         http://www.jb51.net/article/33398.htm

相關文章
相關標籤/搜索