Most efficient way to convert a single char to a C

2020-02-26 14:34发布

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.

6条回答
戒情不戒烟
2楼-- · 2020-02-26 14:56
char c = 'y';
textView.setText(""+c);
查看更多
爷的心禁止访问
3楼-- · 2020-02-26 15:01

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.

查看更多
霸刀☆藐视天下
4楼-- · 2020-02-26 15:03

A solution without concatenation is this:

Character.valueOf(c).toString();
查看更多
再贱就再见
5楼-- · 2020-02-26 15:08
textView.setText(String.valueOf(c))
查看更多
一夜七次
6楼-- · 2020-02-26 15:08

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

查看更多
啃猪蹄的小仙女
7楼-- · 2020-02-26 15:16

Shorthand, as in fewest typed characters possible:

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

In full:

textView.setText(c+"");
查看更多
登录 后发表回答