String and StringBuilder under the String connection operation (2)
Pay attention to the append method of StringBuilder. Use source insight to view the source code provided in Jdk and locate StringBuilder. java searches for the append method to locate an overload of the append method public StringBuilder append (String str) {super. append (str); return this;} indicates that the append method of the parent class is called to locate the append (String str) method of the parent class. Copy the code public synchronized actstringbuilder 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;} the duplicate code str is empty and Len is 0 is not described. Value definition (char array)/*** The value is used for character storage. */char value []; definition of count (used in The array)/*** the count is The number of characters used. */int count; int newCount = count + len; if (newCount> value. length) expandCapacity (newCount ); newCount obtains the new length and the default character array length for comparison. If the length of a string after append exceeds the length of the default value array, it will be resized to copy the code/*** This implements expansion semantics of ensureCapacity with no * size Check or synchronization. */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);} the capacity of the copy code char array is doubled to copy the original data to the new array. The Return Value Type of the append method of the subclass is StringBuilder. The parent class of the subclass is AbstractStringBuilder. The conversion between them involves upward or downward transformation. Other append overload method operations are similar.