How to convert a string to char [] without copying an object?

I have a string and I need to cross 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 creates a new object in memory of type char [] and copies the string object to the new object.

My question is whether it is possible to use a string as char [] without copying the array. My intention is to save on memory. If this is not possible, is there a reason?

Thanks in advance!

+7
java string char java-8
source share
3 answers

No, it is not. With some thought, what you should avoid. Messing with a base char[] in a string through reflection is a recipe for subtle errors. You can access individual characters in a string using charAt , but if you really need char[] , you should just call toCharArray .

If this is not possible, is there a reason?

The first reason is encapsulation. An array is a private implementation detail.

The second reason: immutability. Strings are immutable, but arrays never happen. That way you can change the underlying char array and the string will be mutated, much to the surprise of any developer who relies on normal immutability.

+11
source share

Here's how you can navigate a String somehow like a char array without using toCharArray() :

 for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); } 
+3
source share

Since you are expecting an array to return, there is no way to get an array without creating a new array.

This is the cleanest way. Even though you create your own function and do some kind of trick, you will end up creating a new array.

Go with your current codes.

+3
source share

All Articles