I have a string and I need to traverse it as a char array.
Of course the normal method is to use toCharArray()
String str = "Hello";
char[] charArr = str.toCharArray();
Now, the source code for toCharArray() is as follows.
public char[] toCharArray() {
// Cannot use Arrays.copyOf because of class initialization order issues
char result[] = new char[value.length];
System.arraycopy(value, 0, result, 0, value.length);
return result;
}
So Java is creating a new object in memory of type char[] and copying the string object to the new object.
My question is whether or not it is possible to use a string as a char[] without copying the array. My intention is to save on memory space. If this is not possible, is there a reason so?
Thanks in advance!
No, it isn't. Not without reflection, which you should avoid. Messing with the underlying char[]
in a string via reflection is a recipe for subtle bugs. You can access individual characters in a string using charAt
, but if you really need a char[]
you should just call toCharArray
.
If this is not possible, is there a reason so?
First reason: encapsulation. The array is a private implementation detail.
Second reason: immutability. Strings are immutable, but arrays never are. So you could modify the underlying char array, and the string would be mutated, much to the surprise of any developer relying on the normal immutability.
See more on this question at Stackoverflow