R
Roedy Green
Here is how String.substring works:
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex -
beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex,
value);
}
Note that it now always creates a new string (unless the substring is
the string itself.) It used to create a view into the underlying
string.
So the efficiencies have changed. Substring no longer pins the
underlying big string. On the other hand, you will create many string
objects by using substring. So be careful with it. It is no longer
free in terms of ram to have many substrings of your big string.
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex -
beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex,
value);
}
Note that it now always creates a new string (unless the substring is
the string itself.) It used to create a view into the underlying
string.
So the efficiencies have changed. Substring no longer pins the
underlying big string. On the other hand, you will create many string
objects by using substring. So be careful with it. It is no longer
free in terms of ram to have many substrings of your big string.