JAVA String、StringBuff、StingBuilder
1、可變與不可變
類結(jié)構(gòu)
- String:不可變字符序列
- StringBuff:可變字符序列(線程安全、但是效率低,底層使用插入[ ]存儲(chǔ))
- StringBulider:可變字符序列(線程不安全、效率高、JDK5.0 新增的,底層使用char[]存儲(chǔ))
2、String 源碼
源碼分析:
String str = new String()//char[] value= new char[0]; String str = new String("abc")//char[] value= new char[]{'a','b','c'};3、StringBuff 部分源碼
源碼分析
char[ ] 數(shù)組長度不夠用時(shí),擴(kuò)容底層數(shù)組
默認(rèn)情況下擴(kuò)容為原來的2倍+2,同時(shí)把原有數(shù)組中的元素復(fù)制到新的數(shù)組中
4、StringBulider
線程不安全、效率高
源碼
5、StringBuffer 的方法
1 int capacity()
返回當(dāng)前容量。
2 char charAt(int index)
返回此序列中指定索引處的 char 值。
3 void ensureCapacity(int minimumCapacity)
確保容量至少等于指定的最小值。
4 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
將字符從此序列復(fù)制到目標(biāo)字符數(shù)組 dst。
5 int indexOf(String str)
返回第一次出現(xiàn)的指定子字符串在該字符串中的索引。
6 int indexOf(String str, int fromIndex)
從指定的索引處開始,返回第一次出現(xiàn)的指定子字符串在該字符串中的索引。
7 int lastIndexOf(String str)
返回最右邊出現(xiàn)的指定子字符串在此字符串中的索引。
8 int lastIndexOf(String str, int fromIndex)
返回 String 對(duì)象中子字符串最后出現(xiàn)的位置。
9 int length()
返回長度(字符數(shù))。
10 void setCharAt(int index, char ch)
將給定索引處的字符設(shè)置為 ch。
11 void setLength(int newLength)
設(shè)置字符序列的長度。
12 CharSequence subSequence(int start, int end)
返回一個(gè)新的字符序列,該字符序列是此序列的子序列。
13 String substring(int start)
返回一個(gè)新的 String,它包含此字符序列當(dāng)前所包含的字符子序列。
14 String substring(int start, int end)
返回一個(gè)新的 String,它包含此序列當(dāng)前所包含的字符子序列。
15 String toString()
返回此序列中數(shù)據(jù)的字符串表示形式。
代碼查驗(yàn)
@Testpublic void test4(){StringBuilder sb2 = new StringBuilder("abc");sb2.append(1);sb2.append('1');sb2.append('c');System.out.println("添加后"+sb2);sb2.delete(1, 2);System.out.println("刪除"+sb2);sb2.append("dda", 0,2 );System.out.println("定點(diǎn)添加后"+sb2);sb2.reverse();System.out.println("字符串反轉(zhuǎn)"+sb2);System.out.println("當(dāng)前容量"+sb2.capacity());}運(yùn)行結(jié)果
添加后abc11c 刪除ac11c 定點(diǎn)添加后ac11cdd 字符串反轉(zhuǎn)ddc11ca 當(dāng)前容量19總結(jié):
增 append();
刪 delete();
查 charAt()
改 setCharAt()
插 insert()
長度 length()
遍歷 for() +charAt/toString()
反轉(zhuǎn) reverse()
總結(jié)
以上是生活随笔為你收集整理的JAVA String、StringBuff、StingBuilder的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。