JAVA學習之StringBuffer 與Sring類的區別(例項展示)
阿新 • • 發佈:2018-12-30
一、字串連線方法不同
String 類中用“+”連線,StringBuffer類中用append()方法連線;
例如如下程式碼:
package Test; public class StringDemo01 { public static void main(String[] args) { String str1="Hello"+" "+"World"+"!"; StringBuffer str2=new StringBuffer(); str2.append("Hello"); str2.append(" "); str2.append("World"); str2.append("!"); System.out.println(str1); System.out.println(str2); } }
方法不同,結果相同
二、String 類一旦定義了就不可變了,StringBuffer可以任意改變,這在JAVA筆試中也是易考易錯題。
例如如下程式碼:
package Test; public class StringDemo01 { <span style="WHITE-SPACE: pre"></span>public static void stringReplace (String text) { <span style="WHITE-SPACE: pre"></span> text = text.replace('j' , 'i'); <span style="WHITE-SPACE: pre"></span> } <span style="WHITE-SPACE: pre"></span>public static void bufferReplace (StringBuffer text) { <span style="WHITE-SPACE: pre"></span> text = text.append("C"); <span style="WHITE-SPACE: pre"></span> } <span style="WHITE-SPACE: pre"></span>public static void main(String[] args) { <span style="WHITE-SPACE: pre"></span>String textString = new String ("java"); <span style="WHITE-SPACE: pre"></span> StringBuffer textBuffer = new StringBuffer ("java"); <span style="WHITE-SPACE: pre"></span> stringReplace (textString); <span style="WHITE-SPACE: pre"></span> bufferReplace (textBuffer); <span style="WHITE-SPACE: pre"></span> System.out.println (textString + textBuffer); <span style="WHITE-SPACE: pre"></span> } }
輸出結果是什麼呢?
三、程式中需要對字串進行頻繁的修改連線操作的話.使用StringBuffer效能會更高
package Test; public class StringDemo01 { public static void main(String[] args) { String tempstr ="abcdefghijklmnopqrstuvwxyz"; int times = 5000; long startTime = System.currentTimeMillis(); String str = ""; for(int i=0;i<times;i++){ str += tempstr; } long lendTime = System.currentTimeMillis(); long time = (lendTime - startTime); System.out.println(time); } }
執行時間如下:
如果將程式碼調整為:
package Test;
public class StringDemo01 {
public static void main(String[] args) {
String tempstr ="abcdefghijklmnopqrstuvwxyz";
int times = 5000;
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer();
for(int i=0;i<times;i++){
sb.append(tempstr);
}
long lendTime = System.currentTimeMillis();
long time = (lendTime - startTime);
System.out.println(time);
}
}
執行時間如下:
對比發現,差距不在一個數量級上。