Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: convert a char[] to a CharSequence

Tags:

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

like image 905
Chris Conway Avatar asked Nov 18 '08 18:11

Chris Conway


People also ask

How do you declare a CharSequence in Java?

For example: CharSequence obj = "hello"; String str = "hello"; System. out. println("output is : " + obj + " " + str);

What is CharSequence in Java?

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.

How do I convert a char to a String in Java?

We can convert a char to a string object in java by using the Character. toString() method.

Is CharSequence a String in Java?

CharSequence does not implement String .


3 Answers

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.

like image 111
Tom Hawtin - tackline Avatar answered Oct 11 '22 06:10

Tom Hawtin - tackline


A String is a CharSequence. So you can just create a new String given your char[].

CharSequence seq = new String(arr); 
like image 44
jjnguy Avatar answered Oct 11 '22 07:10

jjnguy


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.

like image 32
Wooff Avatar answered Oct 11 '22 06:10

Wooff