StrngBuffer可變字串

2021-10-12 20:43:03 字數 3398 閱讀 4876

stringbuffer和string區別

stringbuffer和string區別

string 一單被建立後,值就不能改變,如果參與了操作,引用發生了變化,

不是在原有的字串上操作,而是產生了新的字串。

stringbuffer建立後值可以變化(增刪改),位址不會有變化,不會產生新的字串。

stringbuffer加了一把鎖

注意:凡事有利就有弊,犧牲了效能。

stringbuffer的每乙個方法上都有執行緒安全控制

檢視原始碼:

* stringbuffer的api

* stringbuffer()

* 構造乙個沒有字元的字串緩衝區,初始容量為16個字元。

* stringbuffer(charsequence seq)

* 構造乙個包含與指定的相同字元的字串緩衝區 charsequence 。

* stringbuffer(int capacity)

* 構造乙個沒有字元的字串緩衝區和指定的初始容量。

* stringbuffer(string str)

* 構造乙個初始化為指定字串內容的字串緩衝區。

* * //可變字串的追加返回的都是這個可變字串的本省的引用,

* 所以通過鏈式方式來追加**。

將 boolean引數的字串表示附加到序列中。

將 char引數的字串表示附加到此序列。

將 char陣列引數的字串表示附加到此序列。

將 char陣列引數的子陣列的字串表示附加到此序列。

追加指定的 charsequence到這個序列。

追加指定的序列 charsequence到這個序列。

將 double引數的字串表示附加到此序列。

將 float引數的字串表示附加到此序列。

將 int引數的字串表示附加到此序列。

將 long引數的字串表示附加到此序列。

追加 object引數的字串表示。

將指定的字串附加到此字串行。

將指定 stringbuffer這個序列。

將 codepoint引數的字串表示法附加到此序列。

int capacity()

返回當前容量。

stringbuffer stringbuffer.delete(int start, int end)

stringbuffer stringbuffer.deletecharat(int index)

public

class

person12

public

void

setname

(string name)

public

intgetagg()

public

void

setagg

(int agg)

@override

public string tostring()

';}public

person12

(string name,

int agg)

}

stringbuffer sb =

newstringbuffer()

;//追加資料

sb.(10

);sb.

(1.2f);

sb.(1.2);

sb.("qwe");

sb.(new

person12

("網阿萬",12

));//鏈式追加

system.out.

println

(sb)

;//插入

//凡是涉及到索引都要考慮越界的問題

sb.insert(5

,5);

system.out.

println

(sb)

;//刪除 char在這個序列中的指定位置。

sb.deletecharat(3

);system.out.

println

(sb)

;//delete(int start, int end)

//刪除此序列的子字串中的字元。包頭不包尾

sb.delete(0

,3);

system.out.

println

(sb)

; sb.

replace(0

,1,"fdaasdasd");

system.out.

println

(sb)

;//反轉字串

sb.reverse()

; system.out.

println

(sb)

;//按位置索引,返回指定子字串最右邊出現的,字串內的索引。

//獲得乙個子字串在母字串中倒著數第一次出現的索引,從右邊查第一次出現時的位置

int ll =sb.

lastindexof

("gga");

system.out.

println

(ll);//

stringbuffer bt =

newstringbuffer

("helloworldgga123");

//獲得乙個字串在母字串中從指定的索引開始倒數第一次出現的索引

字串 可變字串與不可變字串

一 nsstring 是不可變字串,所有它所有產生其他字串方法都是生成乙個新的字串,而不會改變原來字串 第一種 字面量 它是常量字串,儲存常量區 nsstring str abc 第二種是通過 快捷的構造方法 nsstring stringwithformat 第三種方式 初始化方法 nsstrin...

可變長字串

目錄stringbuilder 其他可變長字串,jdk1.0提供,執行效率慢,執行緒安全字串緩衝區 執行緒安全的可變字串 字串行 字串 如果字串需要頻繁修改,可用stringbuffer構造方法stringbuffer 初始容量為16個字元 stringbuffer int capacity 構造乙...

Java陣列 可變字串行

stringbulider 常用 與stringbuffer 可變字串行 stringbuilder 執行緒不安全,效率高,一般用這個 stringbuffer 執行緒安全 author administrator public class teststringbuilder stringbuild...