What is the most direct and/or efficient way to convert a char[]
into a CharSequence
?
For example: CharSequence obj = "hello"; String str = "hello"; System. out. println("output is : " + obj + " " + str);
A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences. A char value represents a character in the Basic Multilingual Plane (BMP) or a surrogate. Refer to Unicode Character Representation for details.
We can convert a char to a string object in java by using the Character. toString() method.
CharSequence does not implement String .
Without the copy:
CharSequence seq = java.nio.CharBuffer.wrap(array);
However, the new String(array)
approach is likely to be easier to write, easier to read and faster.
A String
is a CharSequence
. So you can just create a new String
given your char[]
.
CharSequence seq = new String(arr);
Context:
One of the most common usage of char[] instead of String, is to "temporary" store secrets/passwords. To pass it to initialization of some service/clients ... The sercrets are not needed after such initialization. But in java string is not possible to clear it from memory (manualy nor by garbage collection)... So, it is basically forbiden to store secrets in Strings.
Recommended way: Load secrets to char[], pass it to init proces, and clear it manually (set forEach char[i] = '0';). Read about this problem on specialized blogs...
Question/Answer:
NOTE: unfortunately, one has to check even 3rd party service/client init source code, it happens that they convert char array to string somewhere deep in their code... )-: Choose your dependencies wisely.
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