Most efficient way to convert a single char to a CharSequence

好久不见. 提交于 2019-11-30 17:03:36
textView.setText(String.valueOf(c))

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

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.

Shorthand, as in fewest typed characters possible:

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

In full:

textView.setText(c+"");

A solution without concatenation is this:

Character.valueOf(c).toString();
char c = 'y';
textView.setText(""+c);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!