java基础源码 (2)--StringBuilder类
Serializable(接口):
是一个IO的序列化接口,实现了这个接口,就代表这个类可以序列化或者反序列化,该接口没有方法或者字段,仅用于标识可串行话的语义。
Appendable(接口):
/**
* An object to which <tt>char</tt> sequences and values can be appended. The
* <tt>Appendable</tt> interface must be implemented by any class whose
* instances are intended to receive formatted output from a {@link
* java.util.Formatter}.
可附加char序列和值得对象,Appendable接口必须由其实例旨在从Formatter接收格式化输出的类型 *
* <p> The characters to be appended should be valid Unicode characters as
* described in <a href="Character.html#unicode">Unicode Character
* Representation</a>. Note that supplementary characters may be composed of
* multiple 16-bit <tt>char</tt> values.
要附加的字符应为Unicode Character Representation中描述的有效Unicode字符。请注意,
补充字符可以由最多16位char值组成
*
* <p> Appendables are not necessarily safe for multithreaded access. Thread
* safety is the responsibility of classes that extend and implement this
* interface.
*Appendable对于多线程访问,附加功能不一定是安全的。线程安全是扩展和实现这个接口的类的责任
* <p> Since this interface may be implemented by existing classes
* with different styles of error handling there is no guarantee that
* errors will be propagated to the invoker.
由于此接口可能由具有不同样式的错误处理的现有类实现,因此不能保证将错误传播到调用者
*/
public interface Appendable { /**
* Appends the specified character sequence to this <tt>Appendable</tt>.
*将制定的字符序列追加到此Appendable
* <p> Depending on which class implements the character sequence
* <tt>csq</tt>, the entire sequence may not be appended. For
* instance, if <tt>csq</tt> is a {@link java.nio.CharBuffer} then
* the subsequence to append is defined by the buffer's position and limit.
*根据那个类实现字符序列csq,可能不会附加整个序列,假如,如果csq是CharBuff,则附加的子序列
由缓冲区的位置和限制来定义。
* @param csq
* The character sequence to append. If <tt>csq</tt> is
要追加的字符序列,如果csq是null
* <tt>null</tt>, then the four characters <tt>"null"</tt> are
则四个字符“null”附加到该附录
* appended to this Appendable.
*
* @return A reference to this <tt>Appendable</tt>
*
* @throws IOException
* If an I/O error occurs
*/
Appendable append(CharSequence csq) throws IOException; /**
* Appends a subsequence of the specified character sequence to this
* <tt>Appendable</tt>.
*将制定的字符序列的子序列附加到此Appendable
* <p> An invocation of this method of the form <tt>out.append(csq, start,
* end)</tt> when <tt>csq</tt> is not <tt>null</tt>, behaves in
* exactly the same way as the invocation
*形式的这种方法调用out.append(csq,start,end)csq不是null,行为以完全相同的方式调用
out.append(csq.subSequence(start,end))
* <pre>
* out.append(csq.subSequence(start, end)) </pre>
*
* @param csq
* The character sequence from which a subsequence will be
* appended. If <tt>csq</tt> is <tt>null</tt>, then characters
* will be appended as if <tt>csq</tt> contained the four
* characters <tt>"null"</tt>.
追加子序列的字符序列,如果csq是null,则会附加字符,如果csq包含四个字符“null”
*
* @param start
* The index of the first character in the subsequence
子序列中第一个字符的索引
*
* @param end
* The index of the character following the last character in the
* subsequence
子序列中最后一个字符后面的字符的索引
*
* @return A reference to this <tt>Appendable</tt>
*
* @throws IndexOutOfBoundsException
* If <tt>start</tt> or <tt>end</tt> are negative, <tt>start</tt>
* is greater than <tt>end</tt>, or <tt>end</tt> is greater than
* <tt>csq.length()</tt>
如果start或end为负数,则start大于end,或end大于csq.length()都会抛出异常
*
* @throws IOException
* If an I/O error occurs
*/
Appendable append(CharSequence csq, int start, int end) throws IOException; /**
* Appends the specified character to this <tt>Appendable</tt>.
将制定的字符附加到此Appendable
*
* @param c
* The character to append
*
* @return A reference to this <tt>Appendable</tt>
*
* @throws IOException
* If an I/O error occurs
*/
Appendable append(char c) throws IOException;
}
CharSequence(接口):
这个接口String类也是有实现的,该接口是char值得可读序列。
AbstractStringBuilder(类):
/**
* A mutable sequence of characters.
是一个可变的字符序列列表
* <p>
* Implements a modifiable string. At any point in time it contains some
* particular sequence of characters, but the length and content of the
* sequence can be changed through certain method calls.
实现可以修改的字符串,它都包含一些特定的字符列表,长度和内容的序列可以调用某些方法来改变
*
* <p>Unless otherwise noted, passing a {@code null} argument to a constructor
* or method in this class will cause a {@link NullPointerException} to be
* thrown.
构造器的参数如果传null,此类讲抛出NullPointerException异常
*/
abstract class AbstractStringBuilder implements Appendable, CharSequence {
/**
* The value is used for character storage.
类的成员变量:存储字符
*/
char[] value; /**
* The count is the number of characters used.
类的成员变量:有多少个有效数据
*/
int count; /**
* 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];
} /**
* Returns the length (character count).
返回字符长度
*
* @return the length of the sequence of characters currently
* represented by this object
返回字符序列的长度
*/
@Override
public int length() {
return count;
} /**
* Returns the current capacity. The capacity is the amount of storage
* available for newly inserted characters, beyond which an allocation
* will occur.
返回存储序列数组的长度,
*
* @return the current capacity
*/
public int capacity() {
return value.length;
} /**
* Ensures that the capacity is at least equal to the specified minimum.
* If the current capacity is less than the argument, then a new internal
* array is allocated with greater capacity. The new capacity is the
* larger of:
确保容量至少等于指定的最小值,如果当前容量小于参数,那么新的内部数据分配更大的容量
* <ul>
* <li>The {@code minimumCapacity} argument.
* <li>Twice the old capacity, plus {@code 2}.
* </ul>
* If the {@code minimumCapacity} argument is nonpositive, this
* method takes no action and simply returns.
* Note that subsequent operations on this object can reduce the
* actual capacity below that requested here.
如果参数为非正数,则不采取任何动作,只返回。
*
* @param minimumCapacity the minimum desired capacity.
*/
public void ensureCapacity(int minimumCapacity) {
if (minimumCapacity > 0)
ensureCapacityInternal(minimumCapacity);
} /**
* For positive values of {@code minimumCapacity}, this method
* behaves like {@code ensureCapacity}, however it is never
* synchronized.
* If {@code minimumCapacity} is non positive due to numeric
* overflow, this method throws {@code OutOfMemoryError}.
参数minimumCapacity大于value.length则扩容
*/
private void ensureCapacityInternal(int minimumCapacity) {
// overflow-conscious code
if (minimumCapacity - value.length > 0) {
value = Arrays.copyOf(value,
newCapacity(minimumCapacity));
}
} /**
* The maximum size of array to allocate (unless necessary).
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
要分配的最大数据大小(除非必须要)
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /**
* Returns a capacity at least as large as the given minimum capacity.
* Returns the current capacity increased by the same amount + 2 if
* that suffices.
返回至少给定最小容量一样大的容量,返回当前容量增加相同数量+2
* Will not return a capacity greater than {@code MAX_ARRAY_SIZE}
* unless the given minimum capacity is greater than that.
*不会返回大于MAX_ARRAY_SIZE的,除非给定的最小容量大于此值
* @param minCapacity the desired minimum capacity
minCapacity所需的最小容量
* @throws OutOfMemoryError if minCapacity is less than zero or
* greater than Integer.MAX_VALUE
如果minCapacity小于零或者大于interger.MAX_VALUE就会抛出异常
*/
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;
} /**
* Attempts to reduce storage used for the character sequence.
* If the buffer is larger than necessary to hold its current sequence of
如果缓冲区大于保持其当前序列所需的的缓冲区字符
* characters, then it may be resized to become more space efficient.
然后可以根据调整数组的大小提高空间效率
* Calling this method may, but is not required to, affect the value
* returned by a subsequent call to the {@link #capacity()} method.
*/
public void trimToSize() {
if (count < value.length) {
value = Arrays.copyOf(value, count);
}
} /**
* Sets the length of the character sequence.
设置字符序列的长度
* The sequence is changed to a new character sequence
序列更改为新的字符序列
* whose length is specified by the argument. For every nonnegative
其长度有参数指定,对于每个非负
* index <i>k</i> less than {@code newLength}, the character at
index k 小于 newLength , 字符位于
* index <i>k</i> in the new character sequence is the same as the
新字符序列中的 index k
* character at index <i>k</i> in the old sequence if <i>k</i> is less
如果 k 较小,则旧序列中索引 k 处的字符
* than the length of the old character sequence; otherwise, it is the
比旧字符序列的长度,否则,他就是 null 序列
* null character {@code '\u005Cu0000'}.
*
* In other words, if the {@code newLength} argument is less than
换句话说,如果参数newLength小于当前长度
* the current length, the length is changed to the specified length.
长度则更改为newlength
* <p>
* If the {@code newLength} argument is greater than or equal
如果参数newlength参数大于或等于
* to the current length, sufficient null characters
当前长度,足够的空字符
* ({@code '\u005Cu0000'}) are appended so that
附加
* length becomes the {@code newLength} argument.
length成为newLength参数
* <p>
* The {@code newLength} argument must be greater than or equal
newLength参数必须大于或等于
* to {@code 0}.
*
* @param newLength the new length
* @throws IndexOutOfBoundsException if the
* {@code newLength} argument is negative.
*/
public void setLength(int newLength) {
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
ensureCapacityInternal(newLength); if (count < newLength) {
Arrays.fill(value, count, newLength, '\0');
} count = newLength;
} /**
* Returns the {@code char} value in this sequence at the specified index.
返回此序列中指定下标的char值
* The first {@code char} value is at index {@code 0}, the next at index
第一个索引值是从0开始,然后1,以此类推
* {@code 1}, and so on, as in array indexing.
就像在数组索引中一样
* <p>
* The index argument must be greater than or equal to
* {@code 0}, and less than the length of this sequence.
*
* <p>If the {@code char} value specified by the index is a
* <a href="Character.html#unicode">surrogate</a>, the surrogate
* value is returned.
*
* @param index the index of the desired {@code char} value.
* @return the {@code char} value at the specified index.
* @throws IndexOutOfBoundsException if {@code index} is
* negative or greater than or equal to {@code length()}.
*/
@Override
public char charAt(int index) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
return value[index];
} /**
* Returns the character (Unicode code point) at the specified
返回指定的字符
* index. The index refers to {@code char} values
指数。索引引用char值
* (Unicode code units) and ranges from {@code 0} to
* {@link #length()}{@code - 1}.
*
* <p> If the {@code char} value specified at the given index
* is in the high-surrogate range, the following index is less
* than the length of this sequence, and the
* {@code char} value at the following index is in the
* low-surrogate range, then the supplementary code point
* corresponding to this surrogate pair is returned. Otherwise,
* the {@code char} value at the given index is returned.
*
* @param index the index to the {@code char} values
* @return the code point value of the character at the
* {@code index}
* @exception IndexOutOfBoundsException if the {@code index}
* argument is negative or not less than the length of this
* sequence.
*/
public int codePointAt(int index) {
if ((index < 0) || (index >= count)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointAtImpl(value, index, count);
} /**
* Returns the character (Unicode code point) before the specified
* index. The index refers to {@code char} values
* (Unicode code units) and ranges from {@code 1} to {@link
* #length()}.
*
* <p> If the {@code char} value at {@code (index - 1)}
* is in the low-surrogate range, {@code (index - 2)} is not
* negative, and the {@code char} value at {@code (index -
* 2)} is in the high-surrogate range, then the
* supplementary code point value of the surrogate pair is
* returned. If the {@code char} value at {@code index -
* 1} is an unpaired low-surrogate or a high-surrogate, the
* surrogate value is returned.
*
* @param index the index following the code point that should be returned
* @return the Unicode code point value before the given index.
* @exception IndexOutOfBoundsException if the {@code index}
* argument is less than 1 or greater than the length
* of this sequence.
*/
public int codePointBefore(int index) {
int i = index - 1;
if ((i < 0) || (i >= count)) {
throw new StringIndexOutOfBoundsException(index);
}
return Character.codePointBeforeImpl(value, index, 0);
} /**
* Returns the number of Unicode code points in the specified text
* range of this sequence. The text range begins at the specified
* {@code beginIndex} and extends to the {@code char} at
* index {@code endIndex - 1}. Thus the length (in
* {@code char}s) of the text range is
* {@code endIndex-beginIndex}. Unpaired surrogates within
* this sequence count as one code point each.
*
* @param beginIndex the index to the first {@code char} of
* the text range.
* @param endIndex the index after the last {@code char} of
* the text range.
* @return the number of Unicode code points in the specified text
* range
* @exception IndexOutOfBoundsException if the
* {@code beginIndex} is negative, or {@code endIndex}
* is larger than the length of this sequence, or
* {@code beginIndex} is larger than {@code endIndex}.
*/
public int codePointCount(int beginIndex, int endIndex) {
if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
throw new IndexOutOfBoundsException();
}
return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex);
} /**
* Returns the index within this sequence that is offset from the
* given {@code index} by {@code codePointOffset} code
* points. Unpaired surrogates within the text range given by
* {@code index} and {@code codePointOffset} count as
* one code point each.
*
* @param index the index to be offset
* @param codePointOffset the offset in code points
* @return the index within this sequence
* @exception IndexOutOfBoundsException if {@code index}
* is negative or larger then the length of this sequence,
* or if {@code codePointOffset} is positive and the subsequence
* starting with {@code index} has fewer than
* {@code codePointOffset} code points,
* or if {@code codePointOffset} is negative and the subsequence
* before {@code index} has fewer than the absolute value of
* {@code codePointOffset} code points.
*/
public int offsetByCodePoints(int index, int codePointOffset) {
if (index < 0 || index > count) {
throw new IndexOutOfBoundsException();
}
return Character.offsetByCodePointsImpl(value, 0, count,
index, codePointOffset);
} /**
* Characters are copied from this sequence into the
字符从此序列复制到
* destination character array {@code dst}. The first character to
目标字符数组 dst。第一个字符
* be copied is at index {@code srcBegin}; the last character to
被复制在索引,最后一个字符
* be copied is at index {@code srcEnd-1}. The total number of
被复制在索引 srcEnd-1,总数
* characters to be copied is {@code srcEnd-srcBegin}. The
要复制的字符是srcEnd-srcBegin.该字符要被复制到dst的子数组中
* characters are copied into the subarray of {@code dst} starting
* at index {@code dstBegin} and ending at index:
* <pre>{@code
* dstbegin + (srcEnd-srcBegin) - 1
* }</pre>
*
* @param srcBegin start copying at this offset.
* @param srcEnd stop copying at this offset.
* @param dst the array to copy the data into.
* @param dstBegin offset into {@code dst}.
* @throws IndexOutOfBoundsException if any of the following is true:
* <ul>
* <li>{@code srcBegin} is negative
* <li>{@code dstBegin} is negative
* <li>the {@code srcBegin} argument is greater than
* the {@code srcEnd} argument.
* <li>{@code srcEnd} is greater than
* {@code this.length()}.
* <li>{@code dstBegin+srcEnd-srcBegin} is greater than
* {@code dst.length}
* </ul>
*/
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);
} /**
* The character at the specified index is set to {@code ch}. This
指定索引处的字符设置为ch,这个
* sequence is altered to represent a new character sequence that is
序列被改变以表示新的字符序列
* identical to the old character sequence, except that it contains the
与就字符序列相同,但它包含位置 index 的字符
* character {@code ch} at position {@code index}.
* <p>
* The index argument must be greater than or equal to
index参数必须大于0或等于小于此序列的长度
* {@code 0}, and less than the length of this sequence.
*
* @param index the index of the character to modify.
* @param ch the new character.
* @throws IndexOutOfBoundsException if {@code index} is
* negative or greater than or equal to {@code length()}.
*/
public void setCharAt(int index, char ch) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
value[index] = ch;
} /**
* Appends the string representation of the {@code Object} argument.
附加 Object 参数的字符串表示形式
* <p>
* The overall effect is exactly as if the argument were converted
整体效果就像参数被转换一样
* to a string by the method {@link String#valueOf(Object)},
通过String.valueOf(Object)到一个字符串
* and the characters of that string were then
然后那个字符串的字符
* {@link #append(String) appended} to this character sequence.
appended 附加到此字符序列
*
* @param obj an {@code Object}.
* @return a reference to this object.
*/
public AbstractStringBuilder append(Object obj) {
return append(String.valueOf(obj));
} /**
* Appends the specified string to this character sequence.
将指定的字符串追加到此字符序列。
* <p>
* The characters of the {@code String} argument are appended, in
* order, increasing the length of this sequence by the length of the
* argument. If {@code str} is {@code null}, then the four
* characters {@code "null"} are appended.
* <p>
* Let <i>n</i> be the length of this character sequence just prior to
* execution of the {@code append} method. Then the character at
* index <i>k</i> in the new character sequence is equal to the character
* at index <i>k</i> in the old character sequence, if <i>k</i> is less
* than <i>n</i>; otherwise, it is equal to the character at index
* <i>k-n</i> in the argument {@code str}.
*
* @param str a string.
* @return a reference to this object.
*/
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;
} // Documentation in subclasses because of synchro difference
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;
} /**
* @since 1.8
*/
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;
} // Documentation in subclasses because of synchro difference
@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());
} 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;
} /**
* Appends a subsequence of the specified {@code CharSequence} to this
* sequence.
将指定的charSequence的子序列附加到此序列
* <p>
* Characters of the argument {@code s}, starting at
参数的字符s,从
* index {@code start}, are appended, in order, to the contents of
index开始,按顺序附加到内容中
* this sequence up to the (exclusive) index {@code end}. The length
此序列最多为end,
* of this sequence is increased by the value of {@code end - start}.
* <p>
* Let <i>n</i> be the length of this character sequence just prior to
* execution of the {@code append} method. Then the character at
* index <i>k</i> in this character sequence becomes equal to the
* character at index <i>k</i> in this sequence, if <i>k</i> is less than
* <i>n</i>; otherwise, it is equal to the character at index
* <i>k+start-n</i> in the argument {@code s}.
* <p>
* If {@code s} is {@code null}, then this method appends
* characters as if the s parameter was a sequence containing the four
* characters {@code "null"}.
*
* @param s the sequence to append.
* @param start the starting index of the subsequence to be appended.
* @param end the end index of the subsequence to be appended.
* @return a reference to this object.
* @throws IndexOutOfBoundsException if
* {@code start} is negative, or
* {@code start} is greater than {@code end} or
* {@code end} is greater than {@code s.length()}
*/
@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;
} /**
* Appends the string representation of the {@code char} array
往后面追加一个char类型的数组
* argument to this sequence.
* <p>
* The characters of the array argument are appended, in order, to
* the contents of this sequence. The length of this sequence
* increases by the length of the argument.
* <p>
* The overall effect is exactly as if the argument were converted
* to a string by the method {@link String#valueOf(char[])},
* and the characters of that string were then
* {@link #append(String) appended} to this character sequence.
*
* @param str the characters to be appended.
* @return a reference to this object.
*/
public AbstractStringBuilder append(char[] str) {
int len = str.length;
ensureCapacityInternal(count + len);
System.arraycopy(str, 0, value, count, len);
count += len;
return this;
} /**
* Appends the string representation of a subarray of the
追加子数组的字符串表示
* {@code char} array argument to this sequence.
* <p>
* Characters of the {@code char} array {@code str}, starting at
* index {@code offset}, are appended, in order, to the contents
* of this sequence. The length of this sequence increases
* by the value of {@code len}.
* <p>
* The overall effect is exactly as if the arguments were converted
* to a string by the method {@link String#valueOf(char[],int,int)},
* and the characters of that string were then
* {@link #append(String) appended} to this character sequence.
*
* @param str the characters to be appended.
* @param offset the index of the first {@code char} to append.
* @param len the number of {@code char}s to append.
* @return a reference to this object.
* @throws IndexOutOfBoundsException
* if {@code offset < 0} or {@code len < 0}
* or {@code offset+len > str.length}
*/
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;
} /**
* Appends the string representation of the {@code boolean}
追加 布尔类型的字符串表示序列的参数
* argument to the sequence.
* <p>
* The overall effect is exactly as if the argument were converted
* to a string by the method {@link String#valueOf(boolean)},
* and the characters of that string were then
* {@link #append(String) appended} to this character sequence.
*
* @param b a {@code boolean}.
* @return a reference to this object.
*/
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;
} /**
* Appends the string representation of the {@code char}
* argument to this sequence.
* <p>
* The argument is appended to the contents of this sequence.
* The length of this sequence increases by {@code 1}.
* <p>
* The overall effect is exactly as if the argument were converted
* to a string by the method {@link String#valueOf(char)},
* and the character in that string were then
* {@link #append(String) appended} to this character sequence.
*
* @param c a {@code char}.
* @return a reference to this object.
*/
@Override
public AbstractStringBuilder append(char c) {
ensureCapacityInternal(count + 1);
value[count++] = c;
return this;
} /**
* Appends the string representation of the {@code int}
* argument to this sequence.
* <p>
* The overall effect is exactly as if the argument were converted
* to a string by the method {@link String#valueOf(int)},
* and the characters of that string were then
* {@link #append(String) appended} to this character sequence.
*
* @param i an {@code int}.
* @return a reference to this object.
*/
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;
} /**
* Appends the string representation of the {@code long}
* argument to this sequence.
* <p>
* The overall effect is exactly as if the argument were converted
* to a string by the method {@link String#valueOf(long)},
* and the characters of that string were then
* {@link #append(String) appended} to this character sequence.
*
* @param l a {@code long}.
* @return a reference to this object.
*/
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;
} /**
* Appends the string representation of the {@code float}
* argument to this sequence.
* <p>
* The overall effect is exactly as if the argument were converted
* to a string by the method {@link String#valueOf(float)},
* and the characters of that string were then
* {@link #append(String) appended} to this character sequence.
*
* @param f a {@code float}.
* @return a reference to this object.
*/
public AbstractStringBuilder append(float f) {
FloatingDecimal.appendTo(f,this);
return this;
} /**
* Appends the string representation of the {@code double}
* argument to this sequence.
* <p>
* The overall effect is exactly as if the argument were converted
* to a string by the method {@link String#valueOf(double)},
* and the characters of that string were then
* {@link #append(String) appended} to this character sequence.
*
* @param d a {@code double}.
* @return a reference to this object.
*/
public AbstractStringBuilder append(double d) {
FloatingDecimal.appendTo(d,this);
return this;
} /**
* Removes the characters in a substring of this sequence.
删除此序列中的指定的子字符串的字符
* The substring begins at the specified {@code start} and extends to
子字符串从指定的start开始并延伸到
* the character at index {@code end - 1} or to the end of the
end-1或结尾处的字符序列
* sequence if no such character exists. If
如果
* {@code start} is equal to {@code end}, no changes are made.
start等于end,则不做任何更改
*
* @param start The beginning index, inclusive.
* @param end The ending index, exclusive.
* @return This object.
* @throws StringIndexOutOfBoundsException if {@code start}
* is negative, greater than {@code length()}, or
* greater than {@code 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;
}
}
StringBuilder类:
/**
* A mutable sequence of characters. This class provides an API compatible
* with {@code StringBuffer}, but with no guarantee of synchronization.
* This class is designed for use as a drop-in replacement for
* {@code StringBuffer} in places where the string buffer was being
* used by a single thread (as is generally the case). Where possible,
* it is recommended that this class be used in preference to
* {@code StringBuffer} as it will be faster under most implementations.
一个可变的字符序列,此类提供与StringBuffer的API,但不保证同步,此类设计用作简易替换为StringBuffer
在,正在使用由单个线程字符串缓冲区的地方(如通常是这种情况),在可能的情况下,简易使用这个类别优于
StringBuffer,因为它大大多数实现中将更快
*
* <p>The principal operations on a {@code StringBuilder} are the
* {@code append} and {@code insert} methods, which are
* overloaded so as to accept data of any type. Each effectively
* converts a given datum to a string and then appends or inserts the
* characters of that string to the string builder. The
* {@code append} method always adds these characters at the end
* of the builder; the {@code insert} method adds the characters at
* a specified point.
StringBuilder的主要StringBuilder是append和insert方法,它们是重载的,以便接受
任何类型的数据,每个都有效地将给定的数据转换为字符串,然后将该字符串附加或插入字符
串构造器,append方法始终在构造器的末尾添加这些字符,insert方法将insert添加到
指定点
* <p>
* For example, if {@code z} refers to a string builder object
* whose current contents are "{@code start}", then
* the method call {@code z.append("le")} would cause the string
* builder to contain "{@code startle}", whereas
* {@code z.insert(4, "le")} would alter the string builder to
* contain "{@code starlet}".
例如,如果z引用当前内容“start”的字符串构造器对象,那么方法调用z.append("le")将
导致字符串构造器包含“startle”,而z.insert(4,"le")会将字符串构造器更改为包含
“starlet”
* <p>
* In general, if sb refers to an instance of a {@code StringBuilder},
* then {@code sb.append(x)} has the same effect as
* {@code sb.insert(sb.length(), x)}.
一般情况下,如果某人是指的一个实例StringBuilder,则sb.append(x)具有相同的效果
sb.insert(sb.length(),x).
* <p>
* Every string builder has a capacity. As long as the length of the
* character sequence contained in the string builder does not exceed
* the capacity, it is not necessary to allocate a new internal
* buffer. If the internal buffer overflows, it is automatically made larger.
*每个字符串构造器都有一个容器,只要字符串构造器中包含的字符序列的长度不超过容量,则不需要分配
新的内部缓冲区,如果内部缓冲区溢出,则会自动变大
* <p>Instances of {@code StringBuilder} are not safe for
* use by multiple threads. If such synchronization is required then it is
* recommended that {@link java.lang.StringBuffer} be used.
*StringBuilder不能安全使用多线程,如果需要同步,那么简易使用StringBuffer
* <p>Unless otherwise noted, passing a {@code null} argument to a constructor
* or method in this class will cause a {@link NullPointerException} to be
* thrown.
*
* @author Michael McCloskey
* @see java.lang.StringBuffer
* @see java.lang.String
* @since 1.5
*/
public final class StringBuilder
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{ /** use serialVersionUID for interoperability */
static final long serialVersionUID = 4383685877147921099L; /**
* Constructs a string builder with no characters in it and an
构造一个没有字符的字符串构造器和一个初始化容量为16个字符。
* initial capacity of 16 characters.
*/
public StringBuilder() {
super(16);
} /**
* Constructs a string builder with no characters in it and an
构造一个字符串生成器,其中没有字符和capacity参数指定的初始容量
* initial capacity specified by the {@code capacity} argument.
*
* @param capacity the initial capacity.
* @throws NegativeArraySizeException if the {@code capacity}
* argument is less than {@code 0}.
*/
public StringBuilder(int capacity) {
super(capacity);
} /**
* Constructs a string builder initialized to the contents of the
初始化一个字符串长度为16的
* specified string. The initial capacity of the string builder is
* {@code 16} plus the length of the string argument.
*
* @param str the initial contents of the buffer.
*/
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
} /**
* Constructs a string builder that contains the same characters
构造一个包含与指定的相同字符的字符串构造器CharSequence
* as the specified {@code CharSequence}. The initial capacity of
* the string builder is {@code 16} plus the length of the
* {@code CharSequence} argument.
*
* @param seq the sequence to copy.
*/
public StringBuilder(CharSequence seq) {
this(seq.length() + 16);
append(seq);
} @Override
public StringBuilder append(Object obj) {
return append(String.valueOf(obj));
} @Override
public StringBuilder append(String str) {
super.append(str);
return this;
} /**
* Appends the specified {@code StringBuffer} to this sequence.
将指定StringBuffer这个序列
* <p>
* The characters of the {@code StringBuffer} argument are appended,
* in order, to this sequence, increasing the
* length of this sequence by the length of the argument.
* If {@code sb} is {@code null}, then the four characters
* {@code "null"} are appended to this sequence.
* <p>
* Let <i>n</i> be the length of this character sequence just prior to
* execution of the {@code append} method. Then the character at index
* <i>k</i> in the new character sequence is equal to the character at
* index <i>k</i> in the old character sequence, if <i>k</i> is less than
* <i>n</i>; otherwise, it is equal to the character at index <i>k-n</i>
* in the argument {@code sb}.
*
* @param sb the {@code StringBuffer} to append.
* @return a reference to this object.
*/
public StringBuilder append(StringBuffer sb) {
super.append(sb);
return this;
} @Override
public StringBuilder append(CharSequence s) {
super.append(s);
return this;
} /**
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder append(CharSequence s, int start, int end) {
super.append(s, start, end);
return this;
} @Override
public StringBuilder append(char[] str) {
super.append(str);
return this;
} /**
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder append(char[] str, int offset, int len) {
super.append(str, offset, len);
return this;
} @Override
public StringBuilder append(boolean b) {
super.append(b);
return this;
} @Override
public StringBuilder append(char c) {
super.append(c);
return this;
} @Override
public StringBuilder append(int i) {
super.append(i);
return this;
} @Override
public StringBuilder append(long lng) {
super.append(lng);
return this;
} @Override
public StringBuilder append(float f) {
super.append(f);
return this;
} @Override
public StringBuilder append(double d) {
super.append(d);
return this;
} /**
* @since 1.5
*/
@Override
public StringBuilder appendCodePoint(int codePoint) {
super.appendCodePoint(codePoint);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder delete(int start, int end) {
super.delete(start, end);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder deleteCharAt(int index) {
super.deleteCharAt(index);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder replace(int start, int end, String str) {
super.replace(start, end, str);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int index, char[] str, int offset,
int len)
{
super.insert(index, str, offset, len);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int offset, Object obj) {
super.insert(offset, obj);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int offset, String str) {
super.insert(offset, str);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int offset, char[] str) {
super.insert(offset, str);
return this;
} /**
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int dstOffset, CharSequence s) {
super.insert(dstOffset, s);
return this;
} /**
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int dstOffset, CharSequence s,
int start, int end)
{
super.insert(dstOffset, s, start, end);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int offset, boolean b) {
super.insert(offset, b);
return this;
} /**
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int offset, char c) {
super.insert(offset, c);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int offset, int i) {
super.insert(offset, i);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int offset, long l) {
super.insert(offset, l);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int offset, float f) {
super.insert(offset, f);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
*/
@Override
public StringBuilder insert(int offset, double d) {
super.insert(offset, d);
return this;
} @Override
public int indexOf(String str) {
return super.indexOf(str);
} @Override
public int indexOf(String str, int fromIndex) {
return super.indexOf(str, fromIndex);
} @Override
public int lastIndexOf(String str) {
return super.lastIndexOf(str);
} @Override
public int lastIndexOf(String str, int fromIndex) {
return super.lastIndexOf(str, fromIndex);
} @Override
public StringBuilder reverse() {
super.reverse();
return this;
} @Override
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
} /**
* Save the state of the {@code StringBuilder} instance to a stream
* (that is, serialize it).
*将StringBuilder实例的状态保存到流中,即序列化
* @serialData the number of characters currently stored in the string
* builder ({@code int}), followed by the characters in the
* string builder ({@code char[]}). The length of the
* {@code char} array may be greater than the number of
* characters currently stored in the string builder, in which
* case extra characters are ignored.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
s.writeInt(count);
s.writeObject(value);
} /**
* readObject is called to restore the state of the StringBuffer from
* a stream.
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
count = s.readInt();
value = (char[]) s.readObject();
} }
java基础源码 (2)--StringBuilder类的更多相关文章
- java基础源码 (1)--String类
这个是String类上面的注释,我用谷歌翻译翻译的,虽然有点语法上的问题,但是大概都可以翻译出来 /** * The {@code String} class represents character ...
- java基础源码 (6)--ArrayListt类
原作出处:https://www.cnblogs.com/leesf456/p/5308358.html 简介: 1.ArrayList是一个数组队列,相当于动态数组.与java中的数组相比,它的容量 ...
- Java基础——数组应用之StringBuilder类和StringBuffer类
接上文:Java基础——数组应用之字符串String类 一.StringBuffer类 StringBuffer类和String一样,也用来代表字符串,只是由于StringBuffer的内部实现方式和 ...
- java基础源码 (5)--reflect包-AccessibleObject类
学习参考博客:https://blog.csdn.net/benjaminzhang666/article/details/9664585AccessibleObject类基本作用 1.将反射的对象标 ...
- java基础源码 (3)--Annotation(注解)
借鉴博客地址:https://www.cnblogs.com/skywang12345/p/3344137.html /** * The common interface extended by al ...
- java基础源码 (4)--reflect包-AnnotatedElement接口
接口:AnnotatedElement * Represents an annotated element of the program currently running in this * VM. ...
- 自学Java HashMap源码
自学Java HashMap源码 参考:http://zhangshixi.iteye.com/blog/672697 HashMap概述 HashMap是基于哈希表的Map接口的非同步实现.此实现提 ...
- Java基础-DBCP连接池(BasicDataSource类)详解
Java基础-DBCP连接池(BasicDataSource类)详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 实际开发中“获得连接”或“释放资源”是非常消耗系统资源的两个过程 ...
- java集合源码分析(三):ArrayList
概述 在前文:java集合源码分析(二):List与AbstractList 和 java集合源码分析(一):Collection 与 AbstractCollection 中,我们大致了解了从 Co ...
随机推荐
- ZCGL大数据平台日常运维问题与解决方法
问题:HBase停止 解决方法:重新启动HBase,如下所示 表层问题:插入和查询HBase速度比较慢 排查一,查看HBase节点状态,发现正常运行: 排查二,查看访问HBase服务的状态,发现服务停 ...
- Vue - 引入本地图片的两种方式
第一种,只引入单个图片,这种引入方法在异步中引入则会报错. 比如需要遍历出很多图片展示时 <image :src = require('图片的路径') /> 第二种,可引入多个图片,也可引 ...
- 程序启动:Serialize奋斗史
1.前方高能 在这电子与数据风驰电掣的世界里,人们一刻不停歇的工作着. 但是我却是一个被冷落的人, 因为我做的工作最近用的人太少了.大多数时候,我只能羡慕的看着线程.反射.注解.集合.泛型这些明星员工 ...
- 【Go语言系列】2.2、Go语言基本程序结构:关键字与标识符
什么是标识符 标识符用来命名变量.类型等程序实体.标识符是指Go语言对各种变量.方法.函数等命名时使用的字符序列,标识符由若干个字母.下划线_.和数字组成,且第一个字符必须是字母.通俗的讲就是凡可以自 ...
- 加拿大Assignment写作如何靠第一句话来吸睛?
最近有留学加拿大的同学咨询我们如何写好assignment的首句,关于话题背景的引入,如何才能自然精妙,让老师对后文充满期待.小编用一句话总结今天的策略:陈述一个跟话题直接相关的事实.“直接相关”,保 ...
- MQTT 协议学习:006-订阅主题 与 对应报文(SUBSCRIBE、SUBACK、UNSUBSCRIBE、UNSUBACK)
背景 之前我们提到了怎么发布消息对应的报文:现在我们来看,订阅一个主题的报文是怎么样的. SUBSCRIBE - 订阅主题 客户端向服务端发送SUBSCRIBE报文用于创建一个或多个订阅.每个订阅注册 ...
- uni-app小程序组建
(1)新建组建:编辑器右击 新建组建 (2)传值 <template> <view class="myRankingList"> <block v-f ...
- jenkins -- 安装、任务构建
一.jenkins是什么? Jenkins是一个开源的.提供友好操作界面的持续集成(CI)工具,起源于Hudson(Hudson是商用的),主要用于持续.自动的构建/测试软件项目.监控外部任务的运行( ...
- 2-10 就业课(2.0)-oozie:4、通过oozie执行shell脚本
oozie的配置文件job.properties:里面主要定义的是一些key,value对,定义了一些变量,这些变量往workflow.xml里面传递workflow.xml :workflow的配置 ...
- GoJS组织结构图
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...