The offset/count fields are somewhat orthogonal to the pooling/intern() issues. Offset and count come when you have something like:
String substring = myString.substring(5);
One way to implement this method would be something like:
- allocate a new
char[]withmyString.length() - 5elements - copy all of the elements from index index 5 to
myString.length()from myString to the newchar[] substringis constructed with this newchar[]substring.charAt(i)goes directly tochars[i]substring.length()goes directly tochars.length
As you san see, this approach is O(N) -- where N is the new string's length -- and requires two allocations: the new String, and the new char[]. So instead, substring works by resusing the original char[] but with an offset:
substring.offset=myString.offset + newOffsetsubstring.count=myString.count - newOffset- use
myString.charsas the chars array forsubstringsubstring.charAt(i)goes tochars[i+substring.offset]substring.length()goes tosubstring.count
Note that we didn't need to create a new char[], and more importantly, we didn't need to copy the chars from the old char[] to the new one (since there is no new one). So this operation is just O(1) and requires only one allocation, that of the new String.
Answer from yshavit on Stack OverflowVideos
The offset/count fields are somewhat orthogonal to the pooling/intern() issues. Offset and count come when you have something like:
String substring = myString.substring(5);
One way to implement this method would be something like:
- allocate a new
char[]withmyString.length() - 5elements - copy all of the elements from index index 5 to
myString.length()from myString to the newchar[] substringis constructed with this newchar[]substring.charAt(i)goes directly tochars[i]substring.length()goes directly tochars.length
As you san see, this approach is O(N) -- where N is the new string's length -- and requires two allocations: the new String, and the new char[]. So instead, substring works by resusing the original char[] but with an offset:
substring.offset=myString.offset + newOffsetsubstring.count=myString.count - newOffset- use
myString.charsas the chars array forsubstringsubstring.charAt(i)goes tochars[i+substring.offset]substring.length()goes tosubstring.count
Note that we didn't need to create a new char[], and more importantly, we didn't need to copy the chars from the old char[] to the new one (since there is no new one). So this operation is just O(1) and requires only one allocation, that of the new String.
Java always uses references to any object. There's no way to make it not use references. As for string pooling, that is achieved by the compiler for string literals and at runtime by calling String.intern. It is natural that most of the implementation of String is oblivious to whether it is dealing with an instance referred to by the constant pool or not.