I have a custom CharSequence
implementation and want to implement a toString
with the minimum amount of allocations. And I want it to work in Java 8 and newer versions.
I know I can use a StringBuilder
pre-alocated with the (known) length of my sequence and insert one char at a time. But StringBuilder#toString
will eventually call some String constructor that will copy the builder array. I want to avoid creating this additional array.
My goal was to create a char[]
directly and pass to a non-copying String constructor, and I know I can use SharedSecrets.getJavaLangAccess().newStringUnsafe()
to do that in Java 8, but it has been removed in Java 11. I know that Strings in newer versions are no longer backed by char[]
.
Is there a supported way (Java 8+) of creating a String, char-by-char without creating intermediary objects?