AbstractStringBuilder源码分析
2017-11-26 22:14
260 查看
AbstractStringBuilder源码分析
简介
这个抽象类是StringBuilder和StringBuffer的直接父类,而且定义了很多方法,因此在学习这两个类之间建议先学习 AbstractStringBuilder抽象类该类在源码中注释是以JDK1.5开始作为前两个类的父类存在的,可是直到JDK1.8的API中,关于StringBuilder和StringBuffer的父类还是Object
类声明:
abstract class AbstractStringBuilder implements Appendable, CharSequence
实现了两个接口,其中CharSequence这个字符序列的接口已经很熟悉了:
该接口规定了需要实现该字符序列的长度:length();
可以取得下标为index的的字符:charAt(int index);
可以得到该字符序列的一个子字符序列: subSequence(int start, int end);
规定了该字符序列的String版本(重写了父类Object的toString()):toString();
Appendable接口顾名思义,定义添加的’规则’:
append(CharSequence csq) throws IOException:如何添加一个字符序列
append(CharSequence csq, int start, int end) throws IOException:如何添加一个字符序列的一部分
append(char c) throws IOException:如何添加一个字符
变量:
/** * The value is used for character storage. */ char value[]; /** * The count is the number of characters used. */ int count;
value为该字符序列的具体存储,count为实际存储的数量
注意:(和String中的value和count不同,String中的这两者都是不可变的(final修饰),并且不能对value[]直接操作;而AbstractStringBuilder的两者都是可变的,并且也定义了getValues方法让我们可以直接拿到value[],value实际上是个动态数组,和ArrayList的实现有很多相似的地方)
构造器:
/** * This no-arg constructor is necessary for serialization of subclasses. */ AbstractStringBuilder() { } /** * Creates an AbstractStringBuilder of the specified capacity. */ AbstractStringBuilder(int capacity) { value = new char[capacity]; }
方法(序号是按照方法在源码中出现的顺序来的,所以不是连着的):
1.length():返回已经存储的实际长度(就是count值)public int length() { return count; }
2.capacity():这个单词是’容量’的意思,得到目前该value数组的实际大小
public int capacity() { return value.length; }
3.ensureCapacity(int minimumCapacity):确保value数组的容量是否够用,如果不够用,调用expandCapacity(minimumCapacity)方法扩容,参数为需要的容量
public void ensureCapacity(int minimumCapacity) { if (minimumCapacity > value.length) { expandCapacity(minimumCapacity); } }
4.expandCapacity(int minimumCapacity):对数组进行扩容,参数为需要的容量
void expandCapacity(int minimumCapacity) { int newCapacity = (value.length + 1) * 2; if (newCapacity < 0) { newCapacity = Integer.MAX_VALUE; } else if (minimumCapacity > newCapacity) { newCapacity = minimumCapacity; } value = Arrays.copyOf(value, newCapacity); }
扩容的算法:
如果调用了该函数,说明容量不够用了,先将当前容量+1的二倍(newCapacity)与需要的容量(minimumCapacity)比较。
如果比需要的容量大,那就将容量扩大到容量+1的二倍;如果比需要的容量小,那就直接扩大到需要的容量。
使用Arrays.copyOf()这个非常熟悉的方法来使数组容量动态扩大
5.trimToSize():如果value数组的容量有多余的,那么就把多余的全部都释放掉
public void trimToSize() { if (count < value.length) { value = Arrays.copyOf(value, count); } }
6.setLength(int newLength):强制增大实际长度count的大小,容量如果不够就用 expandCapacity()扩大;将扩大的部分全部用’\0’(ASCII码中的null)来初始化
public void setLength(int newLength) { if (newLength < 0) throw new StringIndexOutOfBoundsException(newLength); if (newLength > value.length) expandCapacity(newLength); if (count < newLength) { for (; count < newLength; count++) value[count] = '\0'; } else { count = newLength; } }
7.charAt(int index):得到下标为index的字符
public char charAt(int index) { if ((index < 0) || (index >= count)) throw new StringIndexOutOfBoundsException(index); return value[index]; }
8.codePointAt(int index):得到代码点
public int codePointAt(int index) { if ((index < 0) || (index >= count)) { throw new StringIndexOutOfBoundsException(index); } return Character.codePointAt(value, index); }
9.getChars(int srcBegin, int srcEnd, char dst[],int dstBegin):将value[]的[srcBegin, srcEnd)拷贝到dst[]数组的desBegin开始处
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); }
24.substring(int start)/substring(int start, int end):得到子字符串
public String substring(int start) { return substring(start, count); } 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); }
25.subSequence(int start, int end):得到一个子字符序列
public CharSequence subSequence(int start, int end) { return substring(start, end); }
36.reverse():将value给倒序存放(注意改变的就是本value,而不是创建了一个新的AbstractStringBuilder然后value为倒序)
public AbstractStringBuilder reverse() { boolean hasSurrogate = false; int n = count - 1; for (int j = (n-1) >> 1; j >= 0; --j) { char temp = value[j]; char temp2 = value[n - j]; if (!hasSurrogate) { hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE) || (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE); } value[j] = temp2; value[n - j] = temp; } if (hasSurrogate) { // Reverse back all valid surrogate pairs 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; } } } } return this; }
toString():唯一的一个抽象方法:toString()
public abstract String toString();
唯一的一个final方法:getValue(),得到value数组。可以对其直接操作
final char[] getValue() { return value; }
CRUD操作:
改:
10.setCharAt(int index, char ch):直接设置下标为index的字符为chpublic void setCharAt(int index, char ch) { if ((index < 0) || (index >= count)) throw new StringIndexOutOfBoundsException(index); value[index] = ch; }
23.replace(int start, int end, String str):用字符串str替换掉value[]数组的[start,end)部分
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); if (newCount > value.length) expandCapacity(newCount); System.arraycopy(value, end, value, start + len, count - end); str.getChars(value, start); count = newCount; return this; }
增(AbstractStringBuilder类及其子类中最重要的操作;Appendable接口的具体实现)
其中append都表示’追加’,insert都表示’插入’:11.append(Object obj):利用Object(或任何对象)的toString方法转成字符串然后添加到该value[]中
public AbstractStringBuilder append(Object obj) { return append(String.valueOf(obj)); }
12.append()的核心代码:append(String str)/append(StringBuffer sb)/append(CharSequence s)。直接修改value[],并且’添加’的意思为链接到原value[]的实际count的后面
public AbstractStringBuilder append(String str) { if (str == null) str = "null"; int len = str.length(); if (len == 0) return this; int newCount = count + len; if (newCount > value.length) expandCapacity(newCount); str.getChars(0, len, value, count); count = newCount; return this; } // Documentation in subclasses because of synchro difference public AbstractStringBuilder append(StringBuffer sb) { if (sb == null) return append("null"); int len = sb.length(); int newCount = count + len; if (newCount > value.length) expandCapacity(newCount); sb.getChars(0, len, value, count); count = newCount; return this; } // Documentation in subclasses because of synchro difference public AbstractStringBuilder append(CharSequence s) { if (s == null) s = "null"; if (s instanceof String) return this.append((String)s); if (s instanceof StringBuffer) return this.append((StringBuffer)s); return this.append(s, 0, s.length()); }
同时注意返回的都是AbstractStringBuilder,意味着append方法可以连续无限调用,即AbstractStringBuilder对象.append(参数1).append(参数2).append(参数三)…………;
13.append(CharSequence s, int start, int end):添加字符序列s的部分序列,范围是[start,end)
public AbstractStringBuilder append(CharSequence s, int start, int end) { if (s == null) s = "null"; 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; if (len == 0) return this; int newCount = count + len; if (newCount > value.length) expandCapacity(newCount); for (int i=start; i<end; i++) value[count++] = s.charAt(i); count = newCount; return this; }
14.append(char str[]):添加一个字符数组
public AbstractStringBuilder append(char str[]) { int newCount = count + str.length; if (newCount > value.length) expandCapacity(newCount); System.arraycopy(str, 0, value, count, str.length); count = newCount; return this; }
15.append(char str[], int offset, int len):添加一个字符数组的一部分,该部分的范围是[offset,offset+len);
public AbstractStringBuilder append(char str[], int offset, int len) { int newCount = count + len; if (newCount > value.length) expandCapacity(newCount); System.arraycopy(str, offset, value, count, len); count = newCount; return this; }
16.append(boolean b):添加布尔值。
public AbstractStringBuilder append(boolean b) { if (b) { int newCount = count + 4; if (newCount > value.length) expandCapacity(newCount); value[count++] = 't'; value[count++] = 'r'; value[count++] = 'u'; value[count++] = 'e'; } else { int newCount = count + 5; if (newCount > value.length) expandCapacity(newCount); value[count++] = 'f'; value[count++] = 'a'; value[count++] = 'l'; value[count++] = 's'; value[count++] = 'e'; } return this; }
17.append(char c):添加一个字符
public AbstractStringBuilder append(char c) { int newCount = count + 1; if (newCount > value.length) expandCapacity(newCount); value[count++] = c; return this; }
18.append(int i):添加一个整数
public AbstractStringBuilder append(int i) { if (i == Integer.MIN_VALUE) { append("-2147483648"); return this; } int appendedLength = (i < 0) ? stringSizeOfInt(-i) + 1 : stringSizeOfInt(i); //stringSizeOfInt方法在下面,得到参数整数的位数。 int spaceNeeded = count + appendedLength; if (spaceNeeded > value.length) expandCapacity(spaceNeeded); Integer.getChars(i, spaceNeeded, value); count = spaceNeeded; return this; } final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE }; static int stringSizeOfInt(int x) { for (int i=0; ; i++) if (x <= sizeTable[i]) return i+1; }
19.append(long l):添加一个长整型的数据,原理同上一个append
public AbstractStringBuilder append(long l) { if (l == Long.MIN_VALUE) { append("-9223372036854775808"); return this; } int appendedLength = (l < 0) ? stringSizeOfLong(-l) + 1 : stringSizeOfLong(l); int spaceNeeded = count + appendedLength; if (spaceNeeded > value.length) expandCapacity(spaceNeeded); Long.getChars(l, spaceNeeded, value); count = spaceNeeded; return this; } // Requires positive x static int stringSizeOfLong(long x) { long p = 10; for (int i=1; i<19; i++) { if (x < p) return i; p = 10*p; } return 19; }
20.append(float f)/append(double d):添加一个浮点数。
public AbstractStringBuilder append(float f) { new FloatingDecimal(f).appendTo(this); return this; } public AbstractStringBuilder append(double d) { new FloatingDecimal(d).appendTo(this); return this; }
以上是append
以下是insert
26.insert(int index, char str[], int offset,int len):(insert的核心代码)在value[]的下标为index位置插入数组str的一部分,该部分的范围为:[offset,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); int newCount = count + len; if (newCount > value.length) expandCapacity(newCount); System.arraycopy(value, index, value, index + len, count - index); System.arraycopy(str, offset, value, index, len); count = newCount; return this; }
27.insert(int offset, Object obj):在value[]的offset位置插入Object(或者说所有对象)的String版。
public AbstractStringBuilder insert(int offset, Object obj) { return insert(offset, String.valueOf(obj)); }
28.insert(int offset, String str):在value[]的offset位置插入字符串
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(); int newCount = count + len; if (newCount > value.length) expandCapacity(newCount); System.arraycopy(value, offset, value, offset + len, count - offset); str.getChars(value, offset); count = newCount; return this; }
29.insert(int offset, char str[]):在value[]的offset位置插入字符数组
public AbstractStringBuilder insert(int offset, char str[]) { if ((offset < 0) || (offset > length())) throw new StringIndexOutOfBoundsException(offset); int len = str.length; int newCount = count + len; if (newCount > value.length) expandCapacity(newCount); System.arraycopy(value, offset, value, offset + len, count - offset); System.arraycopy(str, 0, value, offset, len); count = newCount; return this; }
30.insert(int dstOffset, CharSequence s)/insert(int dstOffset, CharSequence s,int start, int end):插入字符序列
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; if (len == 0) return this; int newCount = count + len; if (newCount > value.length) expandCapacity(newCount); System.arraycopy(value, dstOffset, value, dstOffset + len, count - dstOffset); for (int i=start; i<end; i++) value[dstOffset++] = s.charAt(i); count = newCount; return this; }
31.插入基本类型:除了char是直接插入外,其他都是先转成String,然后调用编号为28的insert方法
public AbstractStringBuilder insert(int offset, boolean b) { return insert(offset, String.valueOf(b)); } public AbstractStringBuilder insert(int offset, char c) { int newCount = count + 1; if (newCount > value.length) expandCapacity(newCount); System.arraycopy(value, offset, value, offset + 1, count - offset); value[offset] = c; count = newCount; 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)); }
删:
21.delete(int start, int end):删掉value数组的[start,end)部分,并将end后面的数据移到start位置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; }
22.deleteCharAt(int index):删除下标为index的数据,并将后面的数据前移一位
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; }
查(其实CRUD前面那几个方法中有一两个也算查找):
32.indexOf(String str):在value[]中找字符串str,若能找到,返回第一个字符串的第一个字符的下标public int indexOf(String str) { return indexOf(str, 0); }
33.从fromIndex开始,在value[]中找字符串str,若能找到,返回第一个字符串的第一个字符的下标
public int indexOf(String str, int fromIndex) { return String.indexOf(value, 0, count, str.toCharArray(), 0, str.length(), fromIndex); }
34.lastIndexOf(String str):从后往前找
public int lastIndexOf(String str) { return lastIndexOf(str, count); }
35.lastIndexOf(String str, int fromIndex):从后往前到fromIndex,找子串str
public int lastIndexOf(String str, int fromIndex) { return String.lastIndexOf(value, 0, count, str.toCharArray(), 0, str.length(), fromIndex); }
相关文章推荐
- Java源码分析之AbstractStringBuilder
- 通过源码分析String、StringBuffer和StringBuilder
- Java StringBuilder和StringBuffer源码分析
- 源码分析----ReentrantLock实现和AbstractQueuedSynchronizer
- AbstractReferenceCountedByteBuf源码分析
- String、StringBuffer、StringBuilder源码分析
- AbstractListView源码分析1
- Java并发包源码学习之AQS框架(四)AbstractQueuedSynchronizer源码分析
- AbstractStringBuilder源码学习
- 深入java String拼接和StringBuffer、StringBuilder(分析源码)
- JDK之ReentrantLock,AbstractQueuedSynchronizer源码分析
- String、StringBuilder、 StringBuffer 深入分析 源码解析
- CharSequence,String ,Stringbuilder和StringBuffer源码分析
- StringBuffer和StringBuilder源码分析
- Lock、ReentrantLock和AbstractQueuedSynchronizer的源码要点分析整理
- Java并发系列之AbstractQueuedSynchronizer源码分析(概要分析)
- Java StringBuffer & StringBuilder 源码分析