一个可变的字符序列。此类提供一个与 StringBuffer 兼容的 API,但不保证同步。该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候(这种情况很普遍)。如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。
在 StringBuilder 上的主要操作是 append 和 insert 方法,可重载这些方法,以接受任意类型的数据。
.
StringBuilder 和 CharSequence之间的关系图如下
StringBuilder 有4个构造方法,都是调用super,使用父类构造法。
无参构造方法是初始容量16,有容量参数的构造方法,
String和CharSequence参数构造方法,
看源码可以看出java的巧妙设计,apend()返回了this对象。
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
public StringBuilder(CharSequence seq) {
this(seq.length() + 16);
append(seq);
}
@Override
public StringBuilder append(CharSequence s) {
super.append(s);
return this;
}
Stringbuilder的方法
StringBuilder append(float f)
StringBuilder append(double d)
StringBuilder append(boolean b)
StringBuilder append(int i)
StringBuilder append(long l)
StringBuilder append(char c)
StringBuilder append(char[] chars)
StringBuilder append(char[] str, int offset, int len)
StringBuilder append(String str)
StringBuilder append(Object obj)
StringBuilder append(StringBuffer sb)
StringBuilder append(CharSequence csq)
StringBuilder append(CharSequence csq, int start, int end)
StringBuilder appendCodePoint(int codePoint)
int capacity()
char charAt(int index)
int codePointAt(int index)
int codePointBefore(int index)
int codePointCount(int start, int end)
StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)
void ensureCapacity(int min)
void getChars(int start, int end, char[] dst, int dstStart)
int indexOf(String subString, int start)
int indexOf(String string)
StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long l)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] ch)
StringBuilder insert(int offset, char[] str, int strOffset, int strLen)
StringBuilder insert(int offset, String str)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, CharSequence s)
StringBuilder insert(int offset, CharSequence s, int start, int end)
int lastIndexOf(String string)
int lastIndexOf(String subString, int start)
int length()
int offsetByCodePoints(int index, int codePointOffset)
StringBuilder replace(int start, int end, String string)
StringBuilder reverse()
void setCharAt(int index, char ch)
void setLength(int length)
CharSequence subSequence(int start, int end)
String substring(int start)
String substring(int start, int end)
String toString()
void trimToSize()
关注两个私有方法和toString(使用String的char数组参数构造)
这两个方法是序列化时使用,(序列化参见)
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
s.writeInt(count);
s.writeObject(value);
}
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
count = s.readInt();
value = (char[]) s.readObject();
}
原文地址:http://blog.51cto.com/8294588/2094166