Feature Request: CharSequence.getChars
Rob Spoor
openjdk at icemanx.nl
Fri Nov 13 21:50:18 UTC 2020
Hi all,
In Java 9, compact strings were added. Ever since, I've been trying to
use getChars instead of charAt for Strings. However, I prefer to also do
the same for StringBuilder and StringBuffer. This can lead to some
special cases. For instance, in Apache Commons I/O:
https://github.com/apache/commons-io/blob/master/src/main/java/org/apache/commons/io/input/CharSequenceReader.java#L232
Is it perhaps not a good idea to add getChars as a default method to
CharSequence? The implementation is simple enough:
default void getChars(int srcBegin, int srcEnd, char[] dst, int
dstBegin) {
Objects.checkFromToIndex(srcBegin, srcEnd, length());
int n = srcEnd - srcBegin;
Objects.checkFromIndexSize(dstBegin, n, dst.length);
for (int i = srcBegin; i < srcEnd; i++) {
dst[dstBegin++] = charAt(i);
}
}
String, StringBuilder and StringBuffer automatically override it with
their own methods, so these won't have to change at all.
I've already worked a bit on this, including more efficient overrides
for CharBuffer and StringCharBuffer. The only other known
implementation, Segment, won't profit much from a custom implementation,
so I skipped it.
Should I continue with my work, or is it something that's considered not
necessary? Adding it would allow a better implementation of
Writer.append. For large CharSequences, that's currently hopelessly
inefficient - first it converts the CharSequence to String, then to
char[]. Instead, it could be implemented like write(String, int, int),
with only one conversion (CharSequence to char[]).
Kind regards,
Rob
More information about the core-libs-dev
mailing list