28

What's the most efficient way to pass a single char to a method expecting a CharSequence?

This is what I've got:

textView.setText(new String(new char[] {c} ));

According to the answers given here, this is a sensible way of doing it where the input is a character array. I was wondering if there was a sneaky shortcut I could apply in the single-char case.

Graham Borland
  • 60,055
  • 21
  • 138
  • 179

7 Answers7

51
textView.setText(String.valueOf(c))
eljenso
  • 16,789
  • 6
  • 57
  • 63
13

Looking at the implementation of the Character.toString(char c) method reveals that they use almost the same code you use:

  public String toString() {
       char buf[] = {value};
       return String.valueOf(buf);
  }

For readability, you should just use Character.toString( c ).

Another efficient way would probably be

new StringBuilder(1).append(c);

It's definitely more efficient that using the + operator because, according to the javadoc:

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method

trutheality
  • 23,114
  • 6
  • 54
  • 68
  • 1
    Thanks for the explanation. I'm going with the accepted answer as I suspect the String class probably has a built-in table of single-character Strings to support the valueOf() functionality efficiently. – Graham Borland Jul 06 '11 at 21:30
4

The most compact CharSequence you can get when you have a handful of chars is the CharBuffer. To initialize this with your char value:

CharBuffer.wrap(new char[]{c});

That being said, using Strings is a fair bit more readable and easy to work with.

Bruce Hamilton
  • 500
  • 4
  • 11
3

Shorthand, as in fewest typed characters possible:

c+""; // where c is a char

In full:

textView.setText(c+"");
Charles Goodwin
  • 6,402
  • 3
  • 34
  • 63
2

A solution without concatenation is this:

Character.valueOf(c).toString();
phlogratos
  • 13,234
  • 1
  • 32
  • 37
1
char c = 'y';
textView.setText(""+c);
Grekz
  • 1,570
  • 15
  • 22
-1

Adding to an answer mentioned above (link), adding an example to make things clearer

char c = 'a';
CharSequence cs = String.valueOf(c);
  • 1
    https://stackoverflow.com/a/6603135/2227743 – Eric Aya Nov 30 '21 at 10:13
  • @EricAya the answer you mention uses textView and setText whose meaning was not clear to me. Hence I made this example, just to make it clearer. I wanted to do this as a comment to original answer only, but I did not have enough reputation. Let me just mention credit to the original answer – Samarth Singhal Nov 30 '21 at 10:57
  • I understand your point of view. Still, `String.valueOf(c)` is the solution to OP's question, and it has already been suggested in the other answer. No need to post it again in my opinion. – Eric Aya Nov 30 '21 at 11:51