Reputation: 55979
What is the most direct and/or efficient way to convert a char[]
into a CharSequence
?
Upvotes: 25
Views: 36397
Reputation: 1107
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.
Upvotes: 4
Reputation: 147124
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.
Upvotes: 41
Reputation: 138864
A String
is a CharSequence
. So you can just create a new String
given your char[]
.
CharSequence seq = new String(arr);
Upvotes: 10