StringBuffer类详解
package com.zp.demo2;
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer sb1 = new StringBuffer();//构造一个其中不带字符的字符串缓冲区(底层是数组存储),初始容量为 16 个字符
StringBuffer sb2 = new StringBuffer("abc"); /*构造一个初始化为内容的字符串缓冲区指定字符串。 字符串缓冲区的初始容量是16加上字符串参数的长度。*/
StringBuffer sb3 = new StringBuffer('a');//当为字符时相当于数字 /*构造一个没有字符的字符串缓冲区.指定的初始容量。*/
StringBuffer sb4 = new StringBuffer(13);//13指定初始缓冲区大小 /*构造一个没有字符的字符串缓冲区.指定的初始容量。*/
}
}
StringBuffer类构造方法:
/**
* Constructs a string buffer with no characters in it and an
* initial capacity of 16 characters.
*/
public StringBuffer() {
super(16);
}
/**
* Constructs a string buffer initialized to the contents of the
* specified string. The initial capacity of the string buffer is
* <code>16</code> plus the length of the string argument.
*
* @param str the initial contents of the buffer.
* @exception NullPointerException if <code>str</code> is <code>null</code>
*/
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
}
/**
* Constructs a string buffer with no characters in it and
* the specified initial capacity.
*
* @param capacity the initial capacity.
* @exception NegativeArraySizeException if the <code>capacity</code>
* argument is less than <code>0</code>.
*/
public StringBuffer(int capacity) {
super(capacity);
}
/**
* Constructs a string buffer that contains the same characters
* as the specified <code>CharSequence</code>. The initial capacity of
* the string buffer is <code>16</code> plus the length of the
* <code>CharSequence</code> argument.
* <p>
* If the length of the specified <code>CharSequence</code> is
* less than or equal to zero, then an empty buffer of capacity
* <code>16</code> is returned.
*
* @param seq the sequence to copy.
* @exception NullPointerException if <code>seq</code> is <code>null</code>
* @since 1.5
*/
public StringBuffer(CharSequence seq) {
this(seq.length() + 16);
append(seq);
}
以上为StringBuffer类的四个构造方法。当不带参数时,构造一个其中不带字符的字符串缓冲区(底层是数组存储),初始容量为 16 个字符。当参数为String类型为,字符串缓冲区的初始容量是16加上字符串参数的长度。当参数类型为整型时, 字符串缓冲区的初始容量是16加上字符串参数的长度。