(源码分析)StringBuilder源码分析

川长思鸟来 2024-04-17 18:39 183阅读 0赞

目录

    • 成员变量
    • 构造方法
      • StringBuilder():无参构造
      • StringBuilder(int capacity):指定初始化容量
      • StringBuilder(String str):字符串转换成StringBuilder
    • 成员方法
      • append方法
        • append(int i)
        • append(long lng)
        • append(char c)
        • append(boolean b)
        • append(float f)
        • append(double d)
        • append(String str)
        • append(Object obj)
        • append(StringBuffer sb)
        • append(CharSequence s)
        • append(char[] str)
      • insert方法
        • insert(int offset, Object obj)
        • insert(int offset, String str)
        • insert(int offset, boolean b)
        • insert(int offset, char c)
        • insert(int offset, int i)
        • insert(int offset, long l)
        • insert(int offset, float f)
        • insert(int offset, double d)
        • insert(int offset, char[] str)
      • delete方法
        • deleteCharAt(int index)
        • delete(int start, int end)
      • indexOf方法
        • indexOf(String str, int fromIndex)
        • indexOf(String str)
      • lastIndexOf方法
        • lastIndexOf(String str)
        • lastIndexOf(String str, int fromIndex)
      • 其他方法
        • toString()
        • replace(int start, int end, String str)
        • reverse()
    • 总结

说明:当前StringBuilder的版本为JDK1.8.0_144

成员变量

  1. char[] value; // 在StringBuilder中字符串都是以字符数组的形式存储
  2. int count; // 在value字符数组中实际存储的大小,初始化为0
  3. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // StringBuilder所能容纳的最大的容量

构造方法

StringBuilder():无参构造

  1. /** * 默认StringBuilder容量为16 */
  2. public StringBuilder() {
  3. super(16);
  4. }
  5. /** * 调用父类AbstractStringBuilder的带参构造方法初始化value字符串数组 */
  6. AbstractStringBuilder(int capacity) {
  7. value = new char[capacity];
  8. }

StringBuilder(int capacity):指定初始化容量

  1. /** * 使用指定的容量初始化StringBuilder */
  2. public StringBuilder(int capacity) {
  3. super(capacity);
  4. }
  5. /** * 调用父类AbstractStringBuilder的带参构造方法初始化value字符串数组 */
  6. AbstractStringBuilder(int capacity) {
  7. value = new char[capacity];
  8. }

StringBuilder(String str):字符串转换成StringBuilder

  1. /** * 指定字符串转换成StringBuilder */
  2. public StringBuilder(String str) {
  3. super(str.length() + 16);
  4. append(str);
  5. }
  6. /** * 调用父类AbstractStringBuilder的带参构造方法初始化value字符串数组 */
  7. AbstractStringBuilder(int capacity) {
  8. value = new char[capacity];
  9. }
  10. /** * 同步方法,将字符串转换成字符数组 */
  11. @Override
  12. public StringBuilder append(String str) {
  13. super.append(str);
  14. return this;
  15. }
  16. /** * 调用父类AbstractStringBuilder的同步方法,将字符串转换成字符数组 */
  17. public AbstractStringBuilder append(String str) {
  18. if (str == null) // 当字符串为null时拼接字符数组
  19. return appendNull();
  20. int len = str.length();
  21. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  22. str.getChars(0, len, value, count); // 数组复制,将str字符串从0开始复制长度为len,到value数组从0开始
  23. count += len;
  24. return this;
  25. }
  26. /** * 当字符串为null时拼接字符数组 */
  27. private AbstractStringBuilder appendNull() {
  28. int c = count;
  29. ensureCapacityInternal(c + 4);
  30. final char[] value = this.value;
  31. value[c++] = 'n';
  32. value[c++] = 'u';
  33. value[c++] = 'l';
  34. value[c++] = 'l';
  35. count = c;
  36. return this;
  37. }
  38. /** * 确保数组的容量足够 */
  39. private void ensureCapacityInternal(int minimumCapacity) {
  40. if (minimumCapacity - value.length > 0) { // 当我需要的最小容量minimumCapacity>value的容量就对value字符数组进行扩容
  41. value = Arrays.copyOf(value, newCapacity(minimumCapacity)); // 先获取新的数组容量,再把老数组中的数据拷贝到新数组中
  42. }
  43. }
  44. /** * 获取新的数组容量,新建容量 = max(value.length*2+2,minimumCapacity),minimumCapacity为所需的容量 */
  45. private int newCapacity(int minCapacity) {
  46. int newCapacity = (value.length << 1) + 2;
  47. if (newCapacity - minCapacity < 0) {
  48. newCapacity = minCapacity;
  49. }
  50. return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
  51. ? hugeCapacity(minCapacity) : newCapacity;
  52. }
  53. /** * 确保新的容量不会超过StringBuilder所能容纳的最大容量MAX_ARRAY_SIZE */
  54. private int hugeCapacity(int minCapacity) {
  55. if (Integer.MAX_VALUE - minCapacity < 0) {
  56. throw new OutOfMemoryError();
  57. }
  58. return (minCapacity > MAX_ARRAY_SIZE) ? minCapacity : MAX_ARRAY_SIZE;
  59. }

成员方法

append方法

append方法执行原理:

1、在对字符数组进行赋值之前都会调用ensureCapacityInternal方法来确保数组容量足够,如果容量不够时,将会扩容至max(value.length*2+2,minimumCapacity),minimumCapacity为所需的容量
2、最后才对字符数组进行赋值

append方法源码:

append(int i)

  1. /** * 拼接int型变量 */
  2. @Override
  3. public StringBuilder append(int i) {
  4. super.append(i);
  5. return this;
  6. }
  7. /** * 拼接int型变量 */
  8. public AbstractStringBuilder append(int i) {
  9. if (i == Integer.MIN_VALUE) {
  10. append("-2147483648");
  11. return this;
  12. }
  13. int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
  14. : Integer.stringSize(i); // 获取拼接i需要占用的容量
  15. int spaceNeeded = count + appendedLength; // StringBuilder中总共需要占用的容量
  16. ensureCapacityInternal(spaceNeeded); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  17. Integer.getChars(i, spaceNeeded, value); // 将需要拼接的int型变量i拼接到value数组中
  18. count = spaceNeeded;
  19. return this;
  20. }

append(long lng)

  1. /** * 拼接long型变量 */
  2. @Override
  3. public StringBuilder append(long lng) {
  4. super.append(lng);
  5. return this;
  6. }
  7. /** * 拼接long型变量 */
  8. public AbstractStringBuilder append(long l) {
  9. if (l == Long.MIN_VALUE) {
  10. append("-9223372036854775808");
  11. return this;
  12. }
  13. int appendedLength = (l < 0) ? Long.stringSize(-l) + 1
  14. : Long.stringSize(l); // 获取拼接l需要占用的容量
  15. int spaceNeeded = count + appendedLength; // StringBuilder中总共需要占用的容量
  16. ensureCapacityInternal(spaceNeeded); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  17. Long.getChars(l, spaceNeeded, value); // 将需要拼接的long型变量l拼接到value数组中
  18. count = spaceNeeded;
  19. return this;
  20. }

append(char c)

  1. /** * 拼接char型字符 */
  2. @Override
  3. public StringBuilder append(char c) {
  4. super.append(c);
  5. return this;
  6. }
  7. /** * 拼接char型字符 */
  8. public AbstractStringBuilder append(char c) {
  9. ensureCapacityInternal(count + 1); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  10. value[count++] = c;
  11. return this;
  12. }

append(boolean b)

  1. /** * 拼接boolean型变量 */
  2. @Override
  3. public StringBuilder append(boolean b) {
  4. super.append(b);
  5. return this;
  6. }
  7. /** * 拼接boolean型变量 */
  8. public AbstractStringBuilder append(boolean b) {
  9. if (b) {
  10. ensureCapacityInternal(count + 4); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  11. value[count++] = 't';
  12. value[count++] = 'r';
  13. value[count++] = 'u';
  14. value[count++] = 'e';
  15. } else {
  16. ensureCapacityInternal(count + 5); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  17. value[count++] = 'f';
  18. value[count++] = 'a';
  19. value[count++] = 'l';
  20. value[count++] = 's';
  21. value[count++] = 'e';
  22. }
  23. return this;
  24. }

append(float f)

  1. /** * 拼接float型变量 */
  2. @Override
  3. public StringBuilder append(float f) {
  4. super.append(f);
  5. return this;
  6. }
  7. /** * 拼接float型变量 */
  8. public AbstractStringBuilder append(float f) {
  9. FloatingDecimal.appendTo(f,this); // 将需要拼接的float型变量f拼接到value数组中
  10. return this;
  11. }

append(double d)

  1. /** * 拼接double型变量 */
  2. @Override
  3. public StringBuilder append(double d) {
  4. super.append(d);
  5. return this;
  6. }
  7. /** * 拼接double型变量 */
  8. public AbstractStringBuilder append(double d) {
  9. FloatingDecimal.appendTo(d,this); // 将需要拼接的double型变量d拼接到value数组中
  10. return this;
  11. }

append(String str)

  1. /** * 拼接String型变量 */
  2. @Override
  3. public StringBuilder append(String str) {
  4. super.append(str);
  5. return this;
  6. }
  7. /** * 拼接String型变量 */
  8. public AbstractStringBuilder append(String str) {
  9. if (str == null) // 当字符串为null时拼接字符数组
  10. return appendNull();
  11. int len = str.length();
  12. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  13. str.getChars(0, len, value, count); // 将需要拼接的String型变量str拼接到value数组中
  14. count += len;
  15. return this;
  16. }

append(Object obj)

  1. /** * 拼接Object型变量 */
  2. @Override
  3. public StringBuilder append(Object obj) {
  4. return append(String.valueOf(obj));
  5. }
  6. /** * 拼接String型变量 */
  7. public AbstractStringBuilder append(String str) {
  8. if (str == null) // 当字符串为null时拼接字符数组
  9. return appendNull();
  10. int len = str.length();
  11. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  12. str.getChars(0, len, value, count); // 将需要拼接的String型变量str拼接到value数组中
  13. count += len;
  14. return this;
  15. }

append(StringBuffer sb)

  1. /** * 拼接StringBuffer型变量 */
  2. public StringBuilder append(StringBuffer sb) {
  3. super.append(sb);
  4. return this;
  5. }
  6. /** * 拼接StringBuffer型变量 */
  7. public AbstractStringBuilder append(StringBuffer sb) {
  8. if (sb == null) // 当传入的StringBuffer变量为null时拼接字符数组
  9. return appendNull();
  10. int len = sb.length();
  11. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  12. sb.getChars(0, len, value, count); // 将需要拼接的StringBuffer型变量str拼接到value数组中
  13. count += len;
  14. return this;
  15. }

append(CharSequence s)

  1. /** * 拼接CharSequence型变量 */
  2. @Override
  3. public StringBuilder append(CharSequence s) {
  4. super.append(s);
  5. return this;
  6. }
  7. /** * 拼接CharSequence型变量 */
  8. @Override
  9. public AbstractStringBuilder append(CharSequence s) {
  10. if (s == null)
  11. return appendNull();
  12. if (s instanceof String) // 判断s是啥类型
  13. return this.append((String)s);
  14. if (s instanceof AbstractStringBuilder)
  15. return this.append((AbstractStringBuilder)s);
  16. return this.append(s, 0, s.length());
  17. }

append(char[] str)

  1. /** * 拼接字符数组 */
  2. @Override
  3. public StringBuilder append(CharSequence s, int start, int end) {
  4. super.append(s, start, end);
  5. return this;
  6. }
  7. /** * 拼接字符数组 */
  8. public AbstractStringBuilder append(char[] str) {
  9. int len = str.length;
  10. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  11. System.arraycopy(str, 0, value, count, len); // 将需要拼接的字符数组拼接到value数组中
  12. count += len;
  13. return this;
  14. }

insert方法

insert方法执行原理:

1、在对字符数组进行插入操作之前都会调用ensureCapacityInternal来确保数组容量足够,如果容量不够时,将会扩容至max(value.length*2+2,minimumCapacity),minimumCapacity为所需的容量
2、将指定插入的字符向后移动len(需要插入的字符长度)个位置
3、最后对字符数组指定插入的位置上进行赋值

insert方法源码:

insert(int offset, Object obj)

  1. /** * 在offset处插入obj */
  2. @Override
  3. public StringBuilder insert(int offset, Object obj) {
  4. super.insert(offset, obj);
  5. return this;
  6. }
  7. /** * 将obj转换成String类型,在offset处插入 */
  8. public AbstractStringBuilder insert(int offset, Object obj) {
  9. return insert(offset, String.valueOf(obj));
  10. }
  11. /** * 在offset处插入obj */
  12. public AbstractStringBuilder insert(int offset, String str) {
  13. if ((offset < 0) || (offset > length()))
  14. throw new StringIndexOutOfBoundsException(offset);
  15. if (str == null)
  16. str = "null";
  17. int len = str.length();
  18. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  19. System.arraycopy(value, offset, value, offset + len, count - offset); // 将value数组offset处到结尾的字符全部向后移动len个位置
  20. str.getChars(value, offset); // 在value数组offset处插入str
  21. count += len;
  22. return this;
  23. }

insert(int offset, String str)

  1. /** * 在offset处插入str */
  2. @Override
  3. public StringBuilder insert(int offset, String str) {
  4. super.insert(offset, str);
  5. return this;
  6. }
  7. /** * 在offset处插入str */
  8. public AbstractStringBuilder insert(int offset, String str) {
  9. if ((offset < 0) || (offset > length()))
  10. throw new StringIndexOutOfBoundsException(offset);
  11. if (str == null)
  12. str = "null";
  13. int len = str.length();
  14. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  15. System.arraycopy(value, offset, value, offset + len, count - offset); // 将value数组offset处到结尾的字符全部向后移动len个位置
  16. str.getChars(value, offset); // 在value数组offset处插入str
  17. count += len;
  18. return this;
  19. }

insert(int offset, boolean b)

  1. /** * 在offset处插入b */
  2. @Override
  3. public StringBuilder insert(int offset, boolean b) {
  4. super.insert(offset, b);
  5. return this;
  6. }
  7. /** * 在offset处插入将b转换成字符串后的字符串 */
  8. public AbstractStringBuilder insert(int offset, boolean b) {
  9. return insert(offset, String.valueOf(b));
  10. }
  11. /** * 在offset处插入str */
  12. public AbstractStringBuilder insert(int offset, String str) {
  13. if ((offset < 0) || (offset > length()))
  14. throw new StringIndexOutOfBoundsException(offset);
  15. if (str == null)
  16. str = "null";
  17. int len = str.length();
  18. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  19. System.arraycopy(value, offset, value, offset + len, count - offset); // 将value数组offset处到结尾的字符全部向后移动len个位置
  20. str.getChars(value, offset); // 在value数组offset处插入str
  21. count += len;
  22. return this;
  23. }

insert(int offset, char c)

  1. /** * 在offset处插入c */
  2. @Override
  3. public StringBuilder insert(int offset, char c) {
  4. super.insert(offset, c);
  5. return this;
  6. }
  7. /** * 在offset处插入c */
  8. public AbstractStringBuilder insert(int offset, char c) {
  9. ensureCapacityInternal(count + 1); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  10. System.arraycopy(value, offset, value, offset + 1, count - offset); // 将value数组offset处到结尾的字符全部向后移动len个位置
  11. value[offset] = c; // 在value数组offset处插入str
  12. count += 1;
  13. return this;
  14. }

insert(int offset, int i)

  1. /** * 在offset处插入i */
  2. @Override
  3. public StringBuilder insert(int offset, int i) {
  4. super.insert(offset, i);
  5. return this;
  6. }
  7. /** * 在offset处插入i */
  8. public AbstractStringBuilder insert(int offset, int i) {
  9. return insert(offset, String.valueOf(i));
  10. }
  11. /** * 在offset处插入str */
  12. public AbstractStringBuilder insert(int offset, String str) {
  13. if ((offset < 0) || (offset > length()))
  14. throw new StringIndexOutOfBoundsException(offset);
  15. if (str == null)
  16. str = "null";
  17. int len = str.length();
  18. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  19. System.arraycopy(value, offset, value, offset + len, count - offset); // 将value数组offset处到结尾的字符全部向后移动len个位置
  20. str.getChars(value, offset); // 在value数组offset处插入str
  21. count += len;
  22. return this;
  23. }

insert(int offset, long l)

  1. /** * 在offset处插入l */
  2. @Override
  3. public StringBuilder insert(int offset, long l) {
  4. super.insert(offset, l);
  5. return this;
  6. }
  7. /** * 在offset处插入l */
  8. public AbstractStringBuilder insert(int offset, long l) {
  9. return insert(offset, String.valueOf(l));
  10. }
  11. /** * 在offset处插入str */
  12. public AbstractStringBuilder insert(int offset, String str) {
  13. if ((offset < 0) || (offset > length()))
  14. throw new StringIndexOutOfBoundsException(offset);
  15. if (str == null)
  16. str = "null";
  17. int len = str.length();
  18. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  19. System.arraycopy(value, offset, value, offset + len, count - offset); // 将value数组offset处到结尾的字符全部向后移动len个位置
  20. str.getChars(value, offset); // 在value数组offset处插入str
  21. count += len;
  22. return this;
  23. }

insert(int offset, float f)

  1. /** * 在offset处插入f */
  2. @Override
  3. public StringBuilder insert(int offset, float f) {
  4. super.insert(offset, f);
  5. return this;
  6. }
  7. /** * 在offset处插入f */
  8. public AbstractStringBuilder insert(int offset, float f) {
  9. return insert(offset, String.valueOf(f));
  10. }
  11. /** * 在offset处插入str */
  12. public AbstractStringBuilder insert(int offset, String str) {
  13. if ((offset < 0) || (offset > length()))
  14. throw new StringIndexOutOfBoundsException(offset);
  15. if (str == null)
  16. str = "null";
  17. int len = str.length();
  18. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  19. System.arraycopy(value, offset, value, offset + len, count - offset); // 将value数组offset处到结尾的字符全部向后移动len个位置
  20. str.getChars(value, offset); // 在value数组offset处插入str
  21. count += len;
  22. return this;
  23. }

insert(int offset, double d)

  1. /** * 在offset处插入d */
  2. @Override
  3. public StringBuilder insert(int offset, double d) {
  4. super.insert(offset, d);
  5. return this;
  6. }
  7. /** * 在offset处插入d */
  8. public AbstractStringBuilder insert(int offset, double d) {
  9. return insert(offset, String.valueOf(d));
  10. }
  11. /** * 在offset处插入str */
  12. public AbstractStringBuilder insert(int offset, String str) {
  13. if ((offset < 0) || (offset > length()))
  14. throw new StringIndexOutOfBoundsException(offset);
  15. if (str == null)
  16. str = "null";
  17. int len = str.length();
  18. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  19. System.arraycopy(value, offset, value, offset + len, count - offset); // 将value数组offset处到结尾的字符全部向后移动len个位置
  20. str.getChars(value, offset); // 在value数组offset处插入str
  21. count += len;
  22. return this;
  23. }

insert(int offset, char[] str)

  1. /** * 在offset处插入str */
  2. @Override
  3. public StringBuilder insert(int offset, char[] str) {
  4. super.insert(offset, str);
  5. return this;
  6. }
  7. /** * 在offset处插入str */
  8. public AbstractStringBuilder insert(int offset, char[] str) {
  9. if ((offset < 0) || (offset > length()))
  10. throw new StringIndexOutOfBoundsException(offset);
  11. int len = str.length;
  12. ensureCapacityInternal(count + len); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  13. System.arraycopy(value, offset, value, offset + len, count - offset); // 将value数组offset处到结尾的字符全部向后移动len个位置
  14. System.arraycopy(str, 0, value, offset, len); // 将str拷贝到value数组中,从offset开始插入
  15. count += len;
  16. return this;
  17. }

delete方法

delete方法执行原理:

1、将需要删除地方后面的元素往前移
2、count减去删除的字符长度

delete方法源码:

deleteCharAt(int index)

  1. /** * 根据索引删除字符元素 */
  2. @Override
  3. public StringBuilder deleteCharAt(int index) {
  4. super.deleteCharAt(index);
  5. return this;
  6. }
  7. /** * 根据索引删除字符元素 */
  8. public AbstractStringBuilder deleteCharAt(int index) {
  9. if ((index < 0) || (index >= count))
  10. throw new StringIndexOutOfBoundsException(index);
  11. System.arraycopy(value, index+1, value, index, count-index-1);
  12. count--;
  13. return this;
  14. }

delete(int start, int end)

  1. /** * 删除指定索引范围的字符元素 */
  2. @Override
  3. public StringBuilder delete(int start, int end) {
  4. super.delete(start, end);
  5. return this;
  6. }
  7. /** * 删除指定索引范围的字符元素 */
  8. public AbstractStringBuilder delete(int start, int end) {
  9. if (start < 0)
  10. throw new StringIndexOutOfBoundsException(start);
  11. if (end > count)
  12. end = count;
  13. if (start > end)
  14. throw new StringIndexOutOfBoundsException();
  15. int len = end - start;
  16. if (len > 0) {
  17. System.arraycopy(value, start+len, value, start, count-end); // 从end到count-end的元素往前移动len个位置,相当于删除start与end之间的字符元素
  18. count -= len;
  19. }
  20. return this;
  21. }

indexOf方法

indexOf方法执行原理:

1、调用String中的indexOf方法来查找指定位置开始第一次出现指定字符串的索引

indexOf方法源码:

indexOf(String str, int fromIndex)

  1. /** * 调用父类AbstractStringBuilder实现的 */
  2. @Override
  3. public int indexOf(String str) {
  4. return super.indexOf(str);
  5. }
  6. /** * 返回索引在这个字符串的第一次出现的指定子字符串,从指定的索引开始 */
  7. public int indexOf(String str, int fromIndex) {
  8. return String.indexOf(value, 0, count, str, fromIndex);
  9. }

indexOf(String str)

  1. /** * 调用父类AbstractStringBuilder实现的 */
  2. @Override
  3. public int indexOf(String str) {
  4. return super.indexOf(str);
  5. }
  6. /** * 返回索引在这个字符串的第一次出现的指定子字符串 */
  7. public int indexOf(String str) {
  8. return indexOf(str, 0);
  9. }

lastIndexOf方法

lastIndexOf方法执行原理:

1、调用String中的lastIndexOf方法来查找指定位置开始最后一次出现指定字符串的索引

lastIndexOf方法源码:

lastIndexOf(String str)

  1. /** * 调用父类AbstractStringBuilder实现的 */
  2. @Override
  3. public int lastIndexOf(String str) {
  4. return super.lastIndexOf(str);
  5. }
  6. /** * 返回索引在这个字符串的最后一次出现的指定子字符串 */
  7. public int lastIndexOf(String str) {
  8. return lastIndexOf(str, count);
  9. }

lastIndexOf(String str, int fromIndex)

  1. /** * 调用父类AbstractStringBuilder实现的 */
  2. @Override
  3. public int lastIndexOf(String str) {
  4. return lastIndexOf(str, count);
  5. }
  6. /** * 返回索引在这个字符串的最后一次出现的指定子字符串,从指定的索引开始 */
  7. public int lastIndexOf(String str, int fromIndex) {
  8. return String.lastIndexOf(value, 0, count, str, fromIndex);
  9. }

其他方法

toString()

toString()执行原理:

1、使用String构造方法创建一个String对象返回

toString()源码:

  1. /** * 使用String构造方法创建一个String对象返回 */
  2. @Override
  3. public String toString() {
  4. return new String(value, 0, count);
  5. }

replace(int start, int end, String str)

replace(int start, int end, String str)执行原理:

1、在对字符数组进行插入操作之前都会调用ensureCapacityInternal来确保数组容量足够,如果容量不够时,将会扩容至max(value.length*2+2,minimumCapacity),minimumCapacity为所需的容量
2、将指定位置替换后面的字符元素往右移动
3、在value数组start处插入str

replace(int start, int end, String str)源码:

  1. /** * 用指定的String中的字符替换此序列的子字符串中的String */
  2. @Override
  3. public StringBuilder replace(int start, int end, String str) {
  4. super.replace(start, end, str);
  5. return this;
  6. }
  7. /** * 用指定的String中的字符替换此序列的子字符串中的String */
  8. public AbstractStringBuilder replace(int start, int end, String str) {
  9. if (start < 0)
  10. throw new StringIndexOutOfBoundsException(start);
  11. if (start > count)
  12. throw new StringIndexOutOfBoundsException("start > length()");
  13. if (start > end)
  14. throw new StringIndexOutOfBoundsException("start > end");
  15. if (end > count)
  16. end = count;
  17. int len = str.length();
  18. int newCount = count + len - (end - start);
  19. ensureCapacityInternal(newCount); // 确保数组的容量足够,如果容量不够,将对value数组进行扩容
  20. System.arraycopy(value, end, value, start + len, count - end); // 将指定位置替换后面的字符元素往右移动
  21. str.getChars(value, start); // 在value数组start处插入str
  22. count = newCount;
  23. return this;
  24. }

reverse()

reverse()执行原理:

1、在for循环中反转字符数组中的元素

reverse()源码:

  1. /** * 反转字符串 */
  2. @Override
  3. public StringBuilder reverse() {
  4. super.reverse();
  5. return this;
  6. }
  7. /** * 反转字符串 */
  8. public AbstractStringBuilder reverse() {
  9. boolean hasSurrogates = false;
  10. int n = count - 1;
  11. for (int j = (n-1) >> 1; j >= 0; j--) {
  12. int k = n - j;
  13. char cj = value[j];
  14. char ck = value[k];
  15. value[j] = ck;
  16. value[k] = cj;
  17. if (Character.isSurrogate(cj) ||
  18. Character.isSurrogate(ck)) {
  19. hasSurrogates = true;
  20. }
  21. }
  22. if (hasSurrogates) {
  23. reverseAllValidSurrogatePairs();
  24. }
  25. return this;
  26. }
  27. private void reverseAllValidSurrogatePairs() {
  28. for (int i = 0; i < count - 1; i++) {
  29. char c2 = value[i];
  30. if (Character.isLowSurrogate(c2)) {
  31. char c1 = value[i + 1];
  32. if (Character.isHighSurrogate(c1)) {
  33. value[i++] = c1;
  34. value[i] = c2;
  35. }
  36. }
  37. }
  38. }

总结

  • StringBuilder是一个可变的字符串,底层使用字符数组来存储数据,实际上数据都以字符的形式储存在字符数组value中
  • StringBuilder默认初始化容量大小为16,在每一次进行添加操作(append、insert)时,都会调用ensureCapacityInternal方法来确保数组容量足够,如果容量不够时,将会扩容至max(value.length*2+2,minimumCapacity),minimumCapacity为所需的容量
  • StringBuilder是一个线程不安全的类,所以说在性能上会比StringBuffer高,但是在多线程环境中会出现安全问题
  • StringBuilder中value字符数组拷贝是通过System.arraycopy()方法来操作的

发表评论

表情:
评论列表 (有 0 条评论,183人围观)

还没有评论,来说两句吧...

相关阅读