views:

4289

answers:

3

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

+5  A: 

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

CharSequence seq = new String(arr);
jjnguy
A: 

CharBuffer.wrap?

Chris Conway
+8  A: 

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.

Tom Hawtin - tackline
I chose the most direct way. yours is probably the most efficient, you can't have both i guess
jjnguy
Direct? More direct not to copy, surely? But the CharBuffer subclass code is probably less well exercised, so might end up being slower.
Tom Hawtin - tackline
I'm not sure why you think CharBuffer.wrap will be slower? Just because the code is less mature? Surely if I'm doing this in a tight loop, I should prefer the copy-free version?
Chris Conway
Using a String is more direct in code than a CharBuffer.wrap
jjnguy
It's well known that going through NIO buffers can be a bit slow (there's an awful lot to inline, and that may not happen as you expect). OTOH, CharSequence is often slower the getChars.
Tom Hawtin - tackline