Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to convert a single char to a CharSequence

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.

like image 554
Graham Borland Avatar asked Jul 06 '11 21:07

Graham Borland


People also ask

Is CharSequence same as String?

A String is one of several concrete classes that implements CharSequence interface. So a String is a CharSequence .

Can we typecast char to String?

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


2 Answers

textView.setText(String.valueOf(c)) 
like image 86
eljenso Avatar answered Sep 28 '22 17:09

eljenso


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

like image 36
trutheality Avatar answered Sep 28 '22 17:09

trutheality