Chris Conway
Chris Conway

Reputation: 55979

Java: convert a char[] to a CharSequence

What is the most direct and/or efficient way to convert a char[] into a CharSequence?

Upvotes: 25

Views: 36397

Answers (3)

Wooff
Wooff

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:

  • if service/cliets API accepts only pass/secret as a string - don't use it (and report bug)
  • if service/cliets API accept char array, use it and clear it
  • if service/cliets API accept CharSequence, java.nio.CharBuffer.wrap(array) could be used and cleared after

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

Tom Hawtin - tackline
Tom Hawtin - tackline

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

jjnguy
jjnguy

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

Related Questions