部分方法没有解释,有疑问或错误的地方,欢迎评论指出
package java.lang;import java.util.Arrays;/*** StringBuffer 主要继承 抽象类AbstractStringBuilder 类* 很多实现方法在AbstractStringBuilder中,关于详解 点击下面链接*/
public final class StringBufferextends AbstractStringBuilderimplements java.io.Serializable, CharSequence
{/*** 比之 StringBuilder , StringBuffer 这个很有意思。* toStringCache 缓存最后一次使用的值,每当StringBuffer被修改,这个值清空*/private transient char[] toStringCache;/** Java的序列化机制是通过判断类的serialVersionUID来验证版本一致性的 */static final long serialVersionUID = 3388685877147921107L;/*** 调用父类构造AbstractStringBuilder (int capacity)*/public StringBuffer() {super(16);}public StringBuffer(int capacity) {super(capacity);}public StringBuffer(String str) {super(str.length() + 16);append(str);}public StringBuffer(CharSequence seq) {this(seq.length() + 16);append(seq);}//修饰一个方法,被修饰的方法称为同步方法,其作用的范围是整个方法,作用的对象是调用这个方法的对象;//长度@Overridepublic synchronized int length() {return count;}//容量@Overridepublic synchronized int capacity() {return value.length;}//确保容量@Overridepublic synchronized void ensureCapacity(int minimumCapacity) {if (minimumCapacity > value.length) {expandCapacity(minimumCapacity);}}/*** @since 1.5*/@Overridepublic synchronized void trimToSize() {super.trimToSize();}/*** @throws IndexOutOfBoundsException {@inheritDoc}* @see #length()*/@Overridepublic synchronized void setLength(int newLength) {toStringCache = null;super.setLength(newLength);}/*** @throws IndexOutOfBoundsException {@inheritDoc}* @see #length()*/@Overridepublic synchronized char charAt(int index) {if ((index < 0) || (index >= count))throw new StringIndexOutOfBoundsException(index);return value[index];}/*** @since 1.5*/@Overridepublic synchronized int codePointAt(int index) {return super.codePointAt(index);}/*** @since 1.5*/@Overridepublic synchronized int codePointBefore(int index) {return super.codePointBefore(index);}/*** @since 1.5*/@Overridepublic synchronized int codePointCount(int beginIndex, int endIndex) {return super.codePointCount(beginIndex, endIndex);}/*** @since 1.5*/@Overridepublic synchronized int offsetByCodePoints(int index, int codePointOffset) {return super.offsetByCodePoints(index, codePointOffset);}/*** @throws IndexOutOfBoundsException {@inheritDoc}*/@Overridepublic synchronized void getChars(int srcBegin, int srcEnd, char[] dst,int dstBegin){super.getChars(srcBegin, srcEnd, dst, dstBegin);}/*** @throws IndexOutOfBoundsException {@inheritDoc}* @see #length()*/@Overridepublic synchronized void setCharAt(int index, char ch) {if ((index < 0) || (index >= count))throw new StringIndexOutOfBoundsException(index);toStringCache = null;value[index] = ch;}@Overridepublic synchronized StringBuffer append(Object obj) {toStringCache = null;super.append(String.valueOf(obj));return this;}@Overridepublic synchronized StringBuffer append(String str) {toStringCache = null;super.append(str);return this;}/*** 很多方法和StringBuilder一样* 和StringBuilder不同的是 StringBuffer的方法都加了synchronized 同步锁* 因此StringBuffer在并发的时候更安全,但是相对效率会变慢*/
}