Skip to content

Commit 8c408c5

Browse files
committed
New public method AbstractStringBuilder::flushToString
1 parent 13b3d2f commit 8c408c5

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/java.base/share/classes/java/lang/AbstractStringBuilder.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2215,4 +2215,37 @@ public AbstractStringBuilder repeat(CharSequence cs, int count) {
22152215
this.count = limit;
22162216
return this;
22172217
}
2218+
2219+
/**
2220+
* Returns a string representing the data in this sequence,
2221+
* then sets the length of the character sequence to zero
2222+
* and reduces the capacity to zero.
2223+
* <p>
2224+
* The {@code String} object that is returned contains the character
2225+
* sequence currently represented by this object. Subsequent
2226+
* changes to this sequence do not affect the contents of the
2227+
* returned {@code String}.
2228+
*
2229+
* @implNote In comparsion to {@link #toString()}, for performance reasons
2230+
* this method prevents the creation of copies of the underlying
2231+
* byte array if possible.
2232+
*
2233+
* @return a string representation of this sequence of characters.
2234+
*
2235+
* @since 26
2236+
*/
2237+
public String build() {
2238+
if (count == 0)
2239+
return "";
2240+
2241+
String string = maybeLatin1 && !isLatin1(coder) || count < value.length >> coder
2242+
? toString() // Create a copy, don't share the array
2243+
: new String(value, coder); // Don't create a copy, transfer ownership of array
2244+
2245+
coder = COMPACT_STRINGS ? LATIN1 : UTF16;
2246+
value = EMPTYVALUE;
2247+
count = 0;
2248+
maybeLatin1 = false;
2249+
return string;
2250+
}
22182251
}

src/java.base/share/classes/java/lang/StringBuffer.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -809,4 +809,11 @@ private void readObject(ObjectInputStream s)
809809
synchronized void getBytes(byte[] dst, int dstBegin, byte coder) {
810810
super.getBytes(dst, dstBegin, coder);
811811
}
812+
813+
@Override
814+
public synchronized String build() {
815+
String string = toStringCache == null ? super.build() : toStringCache;
816+
toStringCache = null;
817+
return string;
818+
}
812819
}

0 commit comments

Comments
 (0)