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.
The most compact CharSequence you can get when you have a handful of chars is the CharBuffer. To initialize this with your char value:
That being said, using Strings is a fair bit more readable and easy to work with.
A solution without concatenation is this:
Looking at the implementation of the
Character.toString(char c)
method reveals that they use almost the same code you use:For readability, you should just use
Character.toString( c )
.Another efficient way would probably be
It's definitely more efficient that using the
+
operator because, according to the javadoc:Shorthand, as in fewest typed characters possible:
In full: