Java 将单个字符转换为 CharSequence 的最有效方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6603084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:07:41  来源:igfitidea点击:

Most efficient way to convert a single char to a CharSequence

javaandroidstringcharcharsequence

提问by Graham Borland

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

将单个字符传递给需要 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.

根据这里给出的答案,这是一种明智的做法,其中输入是字符数组。我想知道是否有可以在单字符情况下应用的偷偷摸摸的快捷方式。

采纳答案by eljenso

textView.setText(String.valueOf(c))

回答by Charles Goodwin

Shorthand, as in fewest typed characters possible:

速记,尽可能使用最少的输入字符:

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

In full:

在全:

textView.setText(c+"");

回答by Grekz

char c = 'y';
textView.setText(""+c);

回答by trutheality

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

查看该Character.toString(char c)方法的实现会发现它们使用的代码几乎与您使用的代码相同:

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

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

为了可读性,您应该只使用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:

+根据 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

Java 语言为字符串连接运算符 ( + ) 以及将其他对象转换为字符串提供了特殊支持。字符串连接是通过StringBuilder(or StringBuffer) 类及其 append 方法实现的

回答by phlogratos

A solution without concatenation is this:

没有串联的解决方案是这样的:

Character.valueOf(c).toString();

回答by Bruce Hamilton

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

当您有少量字符时,您可以获得的最紧凑的 CharSequence 是 CharBuffer。要使用您的 char 值初始化它:

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

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

话虽如此,使用字符串更易读且易于使用。