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