學習筆記,僅供參考
StringBuffer類
StringBuffer是在java.lang包下的一個類,我們使用這個類時不需要導包。這個類被final修飾,也就是說,它是最終類,不能被繼承。它是線程安全的可變字符序列。一個類似於 String 的字符串緩衝區,但不能修改。
- StringBuffer和String的區別
- String是一個不可變的字符序列,一旦被初始化不能被改變。
- StringBuffer是一個可變的字符序列
StringBuffer類的構造方法
public StringBuffer() //無參構造方法
構造一個其中不帶字符的字符串緩衝區,初始容量爲 16 個字符。每個字符串緩衝區都有一定的容量。只要字符串緩衝區所包含的字符序列的長度沒有超出此容量,就無需分配新的內部緩衝區數組。如果內部緩衝區溢出,則此容量自動增大。
public StringBuffer(int capacity) //指定容量的字符串緩衝區對象
構造一個不帶字符,但具有指定初始容量的字符串緩衝區。
public StringBuffer(String str) //指定字符串內容的字符串緩衝區對象
構造一個字符串緩衝區,並將其內容初始化爲指定的字符串內容。
StringBuffer類的方法
capacity
public int capacity()
Returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.
- 返回
- the current capacity
length
public int length()
Returns the length (character count).
- 返回
- the length of the sequence of characters currently represented by this object
舉個例子
package com.guiyang.restudy3;
public class D1StringBuffer {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
System.out.println(sb.length()); //容器中的字符個數,實際值
System.out.println(sb.capacity()); //容器的初始容量,理論值
System.out.println("--------");
StringBuffer sb2 = new StringBuffer(10);
System.out.println(sb2.length());
System.out.println(sb2.capacity());
System.out.println("--------");
StringBuffer sb3 = new StringBuffer("Huang");
System.out.println(sb3.length()); //實際字符的個數
System.out.println(sb3.capacity()); //字符串的length + 初始容量
}
}
輸出:
0
16
--------
0
10
--------
5
21