2.StringBuffer:安全執行緒的可變字串序列

來源:互聯網
上載者:User

標籤:實值型別   com   線程   同步   tty   反轉   normal   void   替換   

一、String、StringBuffer和StringBuilder的區別

1.String是內容不可變的,而StringBuffer和StringBuilder都是內容可變的。

2.StringBuffer是同步的,資料安全,效率低;StringBuilder是不同步的,資料不安全,效率高。

二、StringBuffer的方法

1.添加:append(),insert()

2.刪除:deletecharAt(),delete()

3.替換:replace()

4.反轉:reverse()

5.截取:subString()(傳回值類型String)

三、.StringBuffer和String的相互轉換

 
  1. /* String -- StringBuffer */
  2. //方式1:通過構造方法
  3. String s = "hello";
  4. StringBuffer sb = new StringBuffer(s);
  5.                //方式2:通過append方法
  6. String s2 = "hello";
  7. StringBuffer sb2 = new StringBuffer();
  8. sb2.append(s);
 
  1.                //StringBuffer ---String
  2. //方式1:通過構造方法
  3. StringBuffer buffer = new StringBuffer("hello");
  4. String str = new  String(buffer);
  5. //方式2:通過toString()方法
  6. String str2 = buffer.toString();

四、String和StringBuffer作為形參傳遞(要特別注意)

String做為形參傳遞,效果和基礎資料型別 (Elementary Data Type)一致。

 
  1. public class StringTest {
  2. public static void main(String[] args) {
  3.    String s1 = "hello";
  4.    String s2 = "world";
  5.    System.out.println(s1+"===="+s2);//hello====world
  6.    change(s1,s2);
  7.    System.out.println(s1+"===="+s2);//hello====world
  8.    
  9.    StringBuffer sb1 = new StringBuffer("hello");
  10.    StringBuffer sb2 = new StringBuffer("world");
  11.    System.out.println(sb1+"======"+sb2);//hello====world
  12.    change(sb1,sb2);
  13.    System.out.println(sb1+"======"+sb2);//hello======worldworld
  14. }
  15. public static void change(StringBuffer sb1, StringBuffer sb2) {
  16. sb1 = sb2;
  17. sb2.append(sb1);
  18. }
  19. public static void change(String s1, String s2) {
  20. s1 = s2;
  21. s2 = s1 + s2;
  22. }
  23. }





來自為知筆記(Wiz)

2.StringBuffer:安全執行緒的可變字串序列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.