Java中的String、StringBuilder以及StringBuffer

 一.你瞭解String類嗎?html

 二.深刻理解String、StringBuffer、StringBuilderjava

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

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

一.你瞭解String類嗎?

想要了解一個類,最好的辦法就是看這個類的實現源代碼,String類的實如今數組

\jdk1.6.0_14\src\java\lang\String.java   文件中。安全

打開這個類文件就會發現String類是被final修飾的:多線程

 1 public final class String
 2     implements java.io.Serializable, Comparable<String>, CharSequence
 3 {
 4     /** The value is used for character storage. */
 5     private final char value[];
 6  
 7     /** The offset is the first index of the storage that is used. */
 8     private final int offset;
 9  
10     /** The count is the number of characters in the String. */
11     private final int count;
12  
13     /** Cache the hash code for the string */
14     private int hash; // Default to 0
15  
16     /** use serialVersionUID from JDK 1.0.2 for interoperability */
17     private static final long serialVersionUID = -6849794470754667710L;
18  
19     ......
20  
21 }

從上面能夠看出幾點:app

  1)String類是final類,也即意味着String類不能被繼承,而且它的成員方法都默認爲final方法。在Java中,被final修飾的類是不容許被繼承的,而且該類中的成員方法都默認爲final方法。在早期的JVM實現版本中,被final修飾的方法會被轉爲內嵌調用以提高執行效率。而從Java SE5/6開始,就漸漸擯棄這種方式了。所以在如今的Java SE版本中,不須要考慮用final去提高方法調用效率。只有在肯定不想讓該方法被覆蓋時,纔將方法設置爲final。ide

  2)上面列舉出了String類中全部的成員屬性,從上面能夠看出String類實際上是經過char數組來保存字符串的。性能

  下面再繼續看String類的一些方法實現:

 1 public String substring(int beginIndex, int endIndex) {
 2     if (beginIndex < 0) {
 3         throw new StringIndexOutOfBoundsException(beginIndex);
 4     }
 5     if (endIndex > count) {
 6         throw new StringIndexOutOfBoundsException(endIndex);
 7     }
 8     if (beginIndex > endIndex) {
 9         throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
10     }
11     return ((beginIndex == 0) && (endIndex == count)) ? this :
12         new String(offset + beginIndex, endIndex - beginIndex, value);
13     }
14  
15  public String concat(String str) {
16     int otherLen = str.length();
17     if (otherLen == 0) {
18         return this;
19     }
20     char buf[] = new char[count + otherLen];
21     getChars(0, count, buf, 0);
22     str.getChars(0, otherLen, buf, count);
23     return new String(0, count + otherLen, buf);
24     }
25  
26  public String replace(char oldChar, char newChar) {
27     if (oldChar != newChar) {
28         int len = count;
29         int i = -1;
30         char[] val = value; /* avoid getfield opcode */
31         int off = offset;   /* avoid getfield opcode */
32  
33         while (++i < len) {
34         if (val[off + i] == oldChar) {
35             break;
36         }
37         }
38         if (i < len) {
39         char buf[] = new char[len];
40         for (int j = 0 ; j < i ; j++) {
41             buf[j] = val[off+j];
42         }
43         while (i < len) {
44             char c = val[off + i];
45             buf[i] = (c == oldChar) ? newChar : c;
46             i++;
47         }
48         return new String(0, len, buf);
49         }
50     }
51     return this;

從上面的三個方法能夠看出,不管是substring、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();

  再看下面這段代碼:

1 public class Main {
2          
3     public static void main(String[] args) {
4         StringBuilder stringBuilder = new StringBuilder();
5         for(int i=0;i<10000;i++){
6             stringBuilder.append("hello");
7         }
8     }
9 }

反編譯字節碼文件獲得:

 

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

  

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

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

StringBuilder的insert方法

1 public StringBuilder insert(int index, char str[], int offset,
2                               int len)
3   {
4       super.insert(index, str, offset, len);
5   return this;
6   }

StringBuffer的insert方法:

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

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

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

 1 public class Main {
 2     private static int time = 50000;
 3     public static void main(String[] args) {
 4         testString();
 5         testStringBuffer();
 6         testStringBuilder();
 7         test1String();
 8         test2String();
 9     }
10      
11      
12     public static void testString () {
13         String s="";
14         long begin = System.currentTimeMillis();
15         for(int i=0; i<time; i++){
16             s += "java";
17         }
18         long over = System.currentTimeMillis();
19         System.out.println("操做"+s.getClass().getName()+"類型使用的時間爲:"+(over-begin)+"毫秒");
20     }
21      
22     public static void testStringBuffer () {
23         StringBuffer sb = new StringBuffer();
24         long begin = System.currentTimeMillis();
25         for(int i=0; i<time; i++){
26             sb.append("java");
27         }
28         long over = System.currentTimeMillis();
29         System.out.println("操做"+sb.getClass().getName()+"類型使用的時間爲:"+(over-begin)+"毫秒");
30     }
31      
32     public static void testStringBuilder () {
33         StringBuilder sb = new StringBuilder();
34         long begin = System.currentTimeMillis();
35         for(int i=0; i<time; i++){
36             sb.append("java");
37         }
38         long over = System.currentTimeMillis();
39         System.out.println("操做"+sb.getClass().getName()+"類型使用的時間爲:"+(over-begin)+"毫秒");
40     }
41      
42     public static void test1String () {
43         long begin = System.currentTimeMillis();
44         for(int i=0; i<time; i++){
45             String s = "I"+"love"+"java";
46         }
47         long over = System.currentTimeMillis();
48         System.out.println("字符串直接相加操做:"+(over-begin)+"毫秒");
49     }
50      
51     public static void test2String () {
52         String s1 ="I";
53         String s2 = "love";
54         String s3 = "java";
55         long begin = System.currentTimeMillis();
56         for(int i=0; i<time; i++){
57             String s = s1+s2+s3;
58         }
59         long over = System.currentTimeMillis();
60         System.out.println("字符串間接相加操做:"+(over-begin)+"毫秒");
61     }
62      
63 }
View Code

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

  

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

 1 public class Main {
 2     private static int time = 50000;
 3     public static void main(String[] args) {
 4         testString();
 5         testOptimalString();
 6     }
 7      
 8      
 9     public static void testString () {
10         String s="";
11         long begin = System.currentTimeMillis();
12         for(int i=0; i<time; i++){
13             s += "java";
14         }
15         long over = System.currentTimeMillis();
16         System.out.println("操做"+s.getClass().getName()+"類型使用的時間爲:"+(over-begin)+"毫秒");
17     }
18      
19     public static void testOptimalString () {
20         String s="";
21         long begin = System.currentTimeMillis();
22         for(int i=0; i<time; i++){
23             StringBuilder sb = new StringBuilder(s);
24             sb.append("java");
25             s=sb.toString();
26         }
27         long over = System.currentTimeMillis();
28         System.out.println("模擬JVM優化操做的時間爲:"+(over-begin)+"毫秒");
29     }
30      
31 }
View Code

執行結果:

  

獲得驗證。

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

  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類的說法)

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.下面這段代碼輸出結果爲:

 1 public class Main {
 2     public static void main(String[] args) {
 3         String a = "hello2";
 4         final String b = getHello();
 5         String c = b + 2;
 6         System.out.println((a == c));
 7     }
 8      
 9     public static String getHello() {
10         return "hello";
11     }
12 }

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

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

 

 1 public class Main {
 2     public static void main(String[] args) {
 3         String a = "hello";
 4         String b =  new String("hello");
 5         String c =  new String("hello");
 6         String d = b.intern();  7          
 8         System.out.println(a==b);
 9         System.out.println(b==c);
10         System.out.println(b==d);
11         System.out.println(a==d); 12     }
13 }

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

  

  這裏面涉及到的是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)的區別是什麼?

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

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

 

轉自:https://www.cnblogs.com/dolphin0520/p/3778589.html

相關文章
相關標籤/搜索