The following is a constructor of String class
public String(String original) {
int size = original.count;
char[] originalValue = original.value;
char[] v;
if (originalValue.length > size) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
int off = original.offset;
v = Arrays.copyOfRange(originalValue, off, off+size);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
v = originalValue;
}
this.offset = 0;
this.count = size;
this.value = v;
}
But, I wonder how could
if (originalValue.length > size)
happen? The comment says 'trim the baggage', what does baggage refer to?
Take a look at substring, and you'll see how this can happen.
Take for instance String s1 = "Abcd"; String s2 = s1.substring(3)
. Here s1.size()
is 1, but s1.value.length
is 4. This is because s1.value is the same as s2.value. This is done of performance reasons (substring is running in O(1), since it doesn't need to copy the content of the original String).
Using substring can lead to a memory leak. Say you have a really long String, and you only want to keep a small part of it. If you just use substring, you will actually keep the original string content in memory. Doing String snippet = new String(reallyLongString.substring(x,y))
, prevents you from wasting memory backing a large char array no longer needed.
See also What is the purpose of the expression "new String(...)" in Java? for more explanations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With