探祕Java中的String、StringBuilder以及StringBuffer

探祕Java中String、StringBuilder以及StringBuffer

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

  一.你瞭解String類嗎?

  二.深入理解String、StringBuffer、StringBuilder

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

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

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

  請尊重作者勞動成果,轉載請標明轉載地址:

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

一.你瞭解String類嗎?

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

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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類的一些方法實現:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

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個語句都不陌生,在平時寫代碼的過程中也經常遇到,那麼它們到底有什麼區別和聯繫呢?下面先看幾個例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

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類呢?

  那麼看下面這段代碼:

1

2

3

4

5

6

7

8

9

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

2

3

4

5

6

7

8

9

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方法

1

2

3

4

5

6

public StringBuilder insert(int index, char str[], int offset,

                              int len)

  {

      super.insert(index, str, offset, len);

  return this;

  }

  StringBuffer的insert方法:

1

2

3

4

5

6

public synchronized StringBuffer insert(int index, char str[], int offset,

                                            int len)

    {

        super.insert(index, str, offset, len);

        return this;

    }

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

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優化,看下面這段代碼:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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

1

2

3

4

5

6

7

8

9

10

11

12

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.下面這段代碼的輸出結果是什麼?

1

2

3

4

5

6

7

8

9

10

11

12

13

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)的區別是什麼?

1

2

3

4

5

6

7

8

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操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章