StringBuffer构造函数
//Constructor and Description
StringBuffer()
//Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(CharSequence seq)
//Constructs a string buffer that contains the same characters as the specified CharSequence.
StringBuffer(int capacity)
//Constructs a string buffer with no characters in it and the specified initial capacity.
StringBuffer(String str)
//Constructs a string buffer initialized to the contents of the specified string.
方法
常用函数
StringBuffer sb = new StringBuffer();
//Appends the string representation of the argument to this sequence.
sb.append(123); // = sb.append(String.valueOf(123));
sb.append("abc");
//Returns the current capacity.
sb.capacity();
//Returns the length (character count).
sb.length();
//Returns a string representing the data in this sequence.
sb.toString();
//Returns the char value in this sequence at the specified index.
sb.charAt(int index);
//Compares two StringBuffer instances lexicographically.
sb.compareTo(new StringBuffer("123"));
//Removes the characters in a substring of this sequence.
sb.delete(int start, int end)
//Removes the char at the specified position in this sequence.
sb.deleteCharAt(int index)
//Causes this character sequence to be replaced by the reverse of the sequence.
sb.reverse();
不常用函数
//Ensures that the capacity is at least equal to the specified minimum.
void ensureCapacity(int minimumCapacity)
//Characters are copied from this sequence into the destination character array dst.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
//Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str)
//Inserts the string representation of the argument into this sequence.
StringBuffer insert(int offset, boolean/char/char[]/int/double/...)
//Inserts the string representation of a subarray of the str array argument into this sequence.
StringBuffer insert(int index, char[] str, int offset, int len)
//The character at the specified index is set to ch.
void setCharAt(int index, char ch)
//Sets the length of the character sequence.
void setLength(int newLength)
//Returns a new String that contains a subsequence of characters currently contained in this character sequence.
String substring(int start)
//Returns a new String that contains a subsequence of characters currently contained in this sequence.
String substring(int start, int end)
其他资料
- stringbuffer和stringbuilder哪个效率高,应该使用哪个?
- stringbuffer时线程安全的,因为他的append方法会有同步锁,而stringbuilder时线程不安全的
- 单线程的时候使用stringbuilder,在多线程的时候使用stringbuffer
- StringBuffer和String的优缺点比较
- String的值是不可变的,这就导致每次对String的操作都会生成新的String对象,不仅效率低下,而且大量浪费有限的内存空间。
- StringBuffer是可变类,和线程安全的字符串操作类,任何对它指向的字符串的操作都不会产生新的对象。
- 一般情况下,速度从快到慢:StringBuilder>StringBuffer>String,这种比较是相对的,不是绝对的。
- 总结
(1).如果要操作少量的数据用 = String
(2).单线程操作字符串缓冲区 下操作大量数据 = StringBuilder
(3).多线程操作字符串缓冲区 下操作大量数据 = StringBuffer