Java has StringBuilder for generating strings that grow, but unfortunately most of the API uses String so everything requires conversion with attendant copy overhead.
On a compiler, suppose there is an array of char. Is there any class that can offer a read-only StringView (like C++17 string_view)? If not, I could easily write such as class, but the problem is since everything else deals in strings, some of the benefit would be lost. The idea is to provide something that looks like a String where the constructor is just:
StringView(char[] bigBuffer, int start, int len) {}
and to use the class everywhere a string would be used.
There is an interface for read-only access of String
-like data. It's called CharSequence
, and the String
class implements this interface.
The Java equivalent to the C++ string_view
, is a CharBuffer
, which also implements CharSequence
, so any method that accepts a CharSequence
can be called with a String
or a CharBuffer
(or a StringBuilder
).
Many of the Java APIs already accept CharSequence
instead of String
, e.g. all of the parse()
methods in the java.time
package, as well as Java's regex API.
To create a CharBuffer
in a similar way to how the StringView
constructor works, you call wrap()
:
CharBuffer.wrap(char[] array, int offset, int length)
The new buffer will be backed by the given char array; that is, modifications to the buffer will cause the array to be modified and vice versa.
That javadoc shows that no copying is going on.