简介
- 我们在开发中经常使用的就是StringBuilder和StringBuffer来操作字符串
- 而StringBuilder和StringBuffer都继承自AbstractStringBuilder
唯一的区别就是,在其实现的时候,使用父类的方法,但是子类的覆写方法StringBuffer使用的是关键字synchronized 修饰,其是线程安全的,所以我们在学习StringBuilder和StringBuffer的时候,只需要分析父类AbstractStringBuilder即可
继承体系

AbstractStringBuilder实现了2个接口,分别是CharSequence和Appendable
CharSequence
public interface CharSequence {// 序列的长度int length();// 返回 index 位置的元素char charAt(int index);// 返回从 [index,end) 的子序列CharSequence subSequence(int start, int end);// toString方法public String toString();public default IntStream chars() {class CharIterator implements PrimitiveIterator.OfInt {int cur = 0;public boolean hasNext() {return cur < length();}public int nextInt() {if (hasNext()) {return charAt(cur++);} else {throw new NoSuchElementException();}}@Overridepublic void forEachRemaining(IntConsumer block) {for (; cur < length(); cur++) {block.accept(charAt(cur));}}}return StreamSupport.intStream(() ->Spliterators.spliterator(new CharIterator(),length(),Spliterator.ORDERED),Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED,false);}public default IntStream codePoints() {class CodePointIterator implements PrimitiveIterator.OfInt {int cur = 0;@Overridepublic void forEachRemaining(IntConsumer block) {final int length = length();int i = cur;try {while (i < length) {char c1 = charAt(i++);if (!Character.isHighSurrogate(c1) || i >= length) {block.accept(c1);} else {char c2 = charAt(i);if (Character.isLowSurrogate(c2)) {i++;block.accept(Character.toCodePoint(c1, c2));} else {block.accept(c1);}}}} finally {cur = i;}}public boolean hasNext() {return cur < length();}public int nextInt() {final int length = length();if (cur >= length) {throw new NoSuchElementException();}char c1 = charAt(cur++);if (Character.isHighSurrogate(c1) && cur < length) {char c2 = charAt(cur);if (Character.isLowSurrogate(c2)) {cur++;return Character.toCodePoint(c1, c2);}}return c1;}}return StreamSupport.intStream(() ->Spliterators.spliteratorUnknownSize(new CodePointIterator(),Spliterator.ORDERED),Spliterator.ORDERED,false);}}
Appendable
public interface Appendable { // 执行一个流的调用添加 添加数组 Appendable append(CharSequence csq) throws IOException; // 执行一个有前后节点的添加 Appendable append(CharSequence csq, int start, int end) throws IOException; // 添加单个元素 Appendable append(char c) throws IOException; }AbstractStringBuilder
abstract class AbstractStringBuilder implements Appendable, CharSequence { // 底层使用 char数组 // Java char[] value; // 实际的数量 int count; // 无参构造器 AbstractStringBuilder() { } // 有参构造器 设置初始化容量 AbstractStringBuilder(int capacity) { value = new char[capacity]; } // 返回长度 @Override public int length() { return count; } // 返回数组的全部元素容量 public int capacity() { return value.length; } // 确保容量至少等于指定的最小值。 如果当前的容量小于所述参数, // 则新的内部阵列被分配有更大的容量。 新的容量较大 // 该minimumCapacity说法。 // 旧容量的两倍,再加上2 public void ensureCapacity(int minimumCapacity) { if (minimumCapacity > 0) ensureCapacityInternal(minimumCapacity); } // 如果minimumCapacity>value.length 切换数组容量为minimumCapacity private void ensureCapacityInternal(int minimumCapacity) { // overflow-conscious code if (minimumCapacity - value.length > 0) { value = Arrays.copyOf(value, newCapacity(minimumCapacity)); } } // 数组的最大值 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // 设置最大容量值 private int newCapacity(int minCapacity) { // overflow-conscious code int newCapacity = (value.length << 1) + 2; if (newCapacity - minCapacity < 0) { newCapacity = minCapacity; } return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0) ? hugeCapacity(minCapacity) : newCapacity; } // 设置最大容量值 辅助数组 private int hugeCapacity(int minCapacity) { if (Integer.MAX_VALUE - minCapacity < 0) { // overflow throw new OutOfMemoryError(); } return (minCapacity > MAX_ARRAY_SIZE) ? minCapacity : MAX_ARRAY_SIZE; } // 尝试减少用于字符序列的存储 public void trimToSize() { if (count < value.length) { value = Arrays.copyOf(value, count); } } // 设置新数组的长度 public void setLength(int newLength) { if (newLength < 0) throw new StringIndexOutOfBoundsException(newLength); ensureCapacityInternal(newLength); // 将其他没有元素的位置设置为 '\0' if (count < newLength) { Arrays.fill(value, count, newLength, '\0'); } count = newLength; } // 返回指定位置下标的元素 @Override public char charAt(int index) { if ((index < 0) || (index >= count)) throw new StringIndexOutOfBoundsException(index); return value[index]; } // 返回指定位置之后的字符 public int codePointAt(int index) { if ((index < 0) || (index >= count)) { throw new StringIndexOutOfBoundsException(index); } return Character.codePointAtImpl(value, index, count); } // 返回指定位置之前的字符 public int codePointBefore(int index) { int i = index - 1; if ((i < 0) || (i >= count)) { throw new StringIndexOutOfBoundsException(index); } return Character.codePointBeforeImpl(value, index, 0); } // 返回指定区间的字符的数量 public int codePointCount(int beginIndex, int endIndex) { if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) { throw new IndexOutOfBoundsException(); } return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex); } // 返回此序列,其从给定的偏移处的索引index由codePointOffset代码点 public int offsetByCodePoints(int index, int codePointOffset) { if (index < 0 || index > count) { throw new IndexOutOfBoundsException(); } return Character.offsetByCodePointsImpl(value, 0, count, index, codePointOffset); } // 字符是从该序列到目标字符数组复制dst public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) { if (srcBegin < 0) throw new StringIndexOutOfBoundsException(srcBegin); if ((srcEnd < 0) || (srcEnd > count)) throw new StringIndexOutOfBoundsException(srcEnd); if (srcBegin > srcEnd) throw new StringIndexOutOfBoundsException("srcBegin > srcEnd"); System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin); } // 为指定下标设置指定值 public void setCharAt(int index, char ch) { if ((index < 0) || (index >= count)) throw new StringIndexOutOfBoundsException(index); value[index] = ch; } // 增加元素的操作 public AbstractStringBuilder append(Object obj) { return append(String.valueOf(obj)); } // 增加字符串的操作 public AbstractStringBuilder append(String str) { if (str == null) return appendNull(); int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0, len, value, count); count += len; return this; } // 原理就是数组的拷贝 public AbstractStringBuilder append(StringBuffer sb) { if (sb == null) return appendNull(); int len = sb.length(); ensureCapacityInternal(count + len); sb.getChars(0, len, value, count); count += len; return this; } // 原理就是数组的拷贝 AbstractStringBuilder append(AbstractStringBuilder asb) { if (asb == null) return appendNull(); int len = asb.length(); ensureCapacityInternal(count + len); asb.getChars(0, len, value, count); count += len; return this; } @Override public AbstractStringBuilder append(CharSequence s) { if (s == null) return appendNull(); if (s instanceof String) return this.append((String)s); if (s instanceof AbstractStringBuilder) return this.append((AbstractStringBuilder)s); return this.append(s, 0, s.length()); } // 添加null 操作是添加的一个字符 private AbstractStringBuilder appendNull() { int c = count; ensureCapacityInternal(c + 4); final char[] value = this.value; value[c++] = 'n'; value[c++] = 'u'; value[c++] = 'l'; value[c++] = 'l'; count = c; return this; } @Override public AbstractStringBuilder append(CharSequence s, int start, int end) { if (s == null) s = "null"; if ((start < 0) || (start > end) || (end > s.length())) throw new IndexOutOfBoundsException( "start " + start + ", end " + end + ", s.length() " + s.length()); int len = end - start; ensureCapacityInternal(count + len); for (int i = start, j = count; i < end; i++, j++) value[j] = s.charAt(i); count += len; return this; } public AbstractStringBuilder append(char[] str) { int len = str.length; ensureCapacityInternal(count + len); System.arraycopy(str, 0, value, count, len); count += len; return this; } public AbstractStringBuilder append(char str[], int offset, int len) { if (len > 0) // let arraycopy report AIOOBE for len < 0 ensureCapacityInternal(count + len); System.arraycopy(str, offset, value, count, len); count += len; return this; } // 添加Boolean值 public AbstractStringBuilder append(boolean b) { if (b) { ensureCapacityInternal(count + 4); value[count++] = 't'; value[count++] = 'r'; value[count++] = 'u'; value[count++] = 'e'; } else { ensureCapacityInternal(count + 5); value[count++] = 'f'; value[count++] = 'a'; value[count++] = 'l'; value[count++] = 's'; value[count++] = 'e'; } return this; } // 添加一个字符 @Override public AbstractStringBuilder append(char c) { ensureCapacityInternal(count + 1); value[count++] = c; return this; } public AbstractStringBuilder append(int i) { if (i == Integer.MIN_VALUE) { append("-2147483648"); return this; } int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1 : Integer.stringSize(i); int spaceNeeded = count + appendedLength; ensureCapacityInternal(spaceNeeded); Integer.getChars(i, spaceNeeded, value); count = spaceNeeded; return this; } public AbstractStringBuilder append(long l) { if (l == Long.MIN_VALUE) { append("-9223372036854775808"); return this; } int appendedLength = (l < 0) ? Long.stringSize(-l) + 1 : Long.stringSize(l); int spaceNeeded = count + appendedLength; ensureCapacityInternal(spaceNeeded); Long.getChars(l, spaceNeeded, value); count = spaceNeeded; return this; } public AbstractStringBuilder append(float f) { FloatingDecimal.appendTo(f,this); return this; } public AbstractStringBuilder append(double d) { FloatingDecimal.appendTo(d,this); return this; } // 删除 从start到end的元素 public AbstractStringBuilder delete(int start, int end) { if (start < 0) throw new StringIndexOutOfBoundsException(start); if (end > count) end = count; if (start > end) throw new StringIndexOutOfBoundsException(); int len = end - start; if (len > 0) { System.arraycopy(value, start+len, value, start, count-end); count -= len; } return this; } public AbstractStringBuilder appendCodePoint(int codePoint) { final int count = this.count; if (Character.isBmpCodePoint(codePoint)) { ensureCapacityInternal(count + 1); value[count] = (char) codePoint; this.count = count + 1; } else if (Character.isValidCodePoint(codePoint)) { ensureCapacityInternal(count + 2); Character.toSurrogates(codePoint, value, count); this.count = count + 2; } else { throw new IllegalArgumentException(); } return this; } // 删除指定位置的元素 public AbstractStringBuilder deleteCharAt(int index) { if ((index < 0) || (index >= count)) throw new StringIndexOutOfBoundsException(index); System.arraycopy(value, index+1, value, index, count-index-1); count--; return this; } // 替换元素从 start 到 end 为 str public AbstractStringBuilder replace(int start, int end, String str) { if (start < 0) throw new StringIndexOutOfBoundsException(start); if (start > count) throw new StringIndexOutOfBoundsException("start > length()"); if (start > end) throw new StringIndexOutOfBoundsException("start > end"); if (end > count) end = count; int len = str.length(); int newCount = count + len - (end - start); ensureCapacityInternal(newCount); System.arraycopy(value, end, value, start + len, count - end); str.getChars(value, start); count = newCount; return this; } // 从start截取字符串到末尾 public String substring(int start) { return substring(start, count); } // 截取指定位置字符串 从 start 到 end public CharSequence subSequence(int start, int end) { return substring(start, end); } // 截取指定长度的字符串 public String substring(int start, int end) { if (start < 0) throw new StringIndexOutOfBoundsException(start); if (end > count) throw new StringIndexOutOfBoundsException(end); if (start > end) throw new StringIndexOutOfBoundsException(end - start); return new String(value, start, end - start); } // 插入所述的一个子阵列的字符串表示str数组参数插入此序列中 // 在index处开始插入str,偏移量 offset, 长度为len public AbstractStringBuilder insert(int index, char[] str, int offset, int len) { if ((index < 0) || (index > length())) throw new StringIndexOutOfBoundsException(index); if ((offset < 0) || (len < 0) || (offset > str.length - len)) throw new StringIndexOutOfBoundsException( "offset " + offset + ", len " + len + ", str.length " + str.length); ensureCapacityInternal(count + len); System.arraycopy(value, index, value, index + len, count - index); System.arraycopy(str, offset, value, index, len); count += len; return this; } public AbstractStringBuilder insert(int offset, Object obj) { return insert(offset, String.valueOf(obj)); } public AbstractStringBuilder insert(int offset, String str) { if ((offset < 0) || (offset > length())) throw new StringIndexOutOfBoundsException(offset); if (str == null) str = "null"; int len = str.length(); ensureCapacityInternal(count + len); System.arraycopy(value, offset, value, offset + len, count - offset); str.getChars(value, offset); count += len; return this; } public AbstractStringBuilder insert(int offset, char[] str) { if ((offset < 0) || (offset > length())) throw new StringIndexOutOfBoundsException(offset); int len = str.length; ensureCapacityInternal(count + len); System.arraycopy(value, offset, value, offset + len, count - offset); System.arraycopy(str, 0, value, offset, len); count += len; return this; } public AbstractStringBuilder insert(int dstOffset, CharSequence s) { if (s == null) s = "null"; if (s instanceof String) return this.insert(dstOffset, (String)s); return this.insert(dstOffset, s, 0, s.length()); } public AbstractStringBuilder insert(int dstOffset, CharSequence s, int start, int end) { if (s == null) s = "null"; if ((dstOffset < 0) || (dstOffset > this.length())) throw new IndexOutOfBoundsException("dstOffset "+dstOffset); if ((start < 0) || (end < 0) || (start > end) || (end > s.length())) throw new IndexOutOfBoundsException( "start " + start + ", end " + end + ", s.length() " + s.length()); int len = end - start; ensureCapacityInternal(count + len); System.arraycopy(value, dstOffset, value, dstOffset + len, count - dstOffset); for (int i=start; i<end; i++) value[dstOffset++] = s.charAt(i); count += len; return this; } public AbstractStringBuilder insert(int offset, boolean b) { return insert(offset, String.valueOf(b)); } public AbstractStringBuilder insert(int offset, char c) { ensureCapacityInternal(count + 1); System.arraycopy(value, offset, value, offset + 1, count - offset); value[offset] = c; count += 1; return this; } public AbstractStringBuilder insert(int offset, int i) { return insert(offset, String.valueOf(i)); } public AbstractStringBuilder insert(int offset, long l) { return insert(offset, String.valueOf(l)); } public AbstractStringBuilder insert(int offset, float f) { return insert(offset, String.valueOf(f)); } public AbstractStringBuilder insert(int offset, double d) { return insert(offset, String.valueOf(d)); } // 获取字符串第一次出现的位置 public int indexOf(String str) { return indexOf(str, 0); } // 获取字符串从 fromIndex 第一次出现的位置 public int indexOf(String str, int fromIndex) { return String.indexOf(value, 0, count, str, fromIndex); } // 获取字符串最后一次出现的位置 public int lastIndexOf(String str) { return lastIndexOf(str, count); } // 获取字符串从到数 fromIndex开始出现的第一次的位置 public int lastIndexOf(String str, int fromIndex) { return String.lastIndexOf(value, 0, count, str, fromIndex); } // 反转字符数组 public AbstractStringBuilder reverse() { boolean hasSurrogates = false; int n = count - 1; for (int j = (n-1) >> 1; j >= 0; j--) { int k = n - j; char cj = value[j]; char ck = value[k]; value[j] = ck; value[k] = cj; if (Character.isSurrogate(cj) || Character.isSurrogate(ck)) { hasSurrogates = true; } } if (hasSurrogates) { reverseAllValidSurrogatePairs(); } return this; } // 用于反向概述辅助方法 private void reverseAllValidSurrogatePairs() { for (int i = 0; i < count - 1; i++) { char c2 = value[i]; if (Character.isLowSurrogate(c2)) { char c1 = value[i + 1]; if (Character.isHighSurrogate(c1)) { value[i++] = c1; value[i] = c2; } } } } @Override public abstract String toString(); final char[] getValue() { return value; } }总结
经过对源码的解读,我们发现狠很多方法都是重载方法,其实其底层和ArrayList类似,都是在操作数组
- 只要掌握了 AbstarctStringBuilder这个类,我们就可以直接掌握它的两个子类,这个时候只需要记住哪个是线程安全的即可
- 扩容机制等等,很类似之前讲过的源码。
- 面试中会问这样的问题:为啥String拼接比StringBuilder慢,因为String的拼接底层在JDK5调用的是StringBuffer的append()方法,在JDK5之后调用的是StringBuilder的append()方法,每次拼接都需要从StringBuilder转换为String,效率慢就慢在这里
- Java9中使用 byte 数组替代 char 数组 作为 AbstractStringBuilder 的默认存储方式
