You can use Character.toString(char)
.
(您可以使用Character.toString(char)
。)
Note that this method simply returns a call to String.valueOf(char)
, which also works. (请注意,此方法只返回对String.valueOf(char)
的调用,这也适用。)
As others have noted, string concatenation works as a shortcut as well:
(正如其他人所指出的那样,字符串连接也可以作为一种捷径:)
String s = "" + 's';
But this compiles down to:
(但这归结为:)
String s = new StringBuilder().append("").append('s').toString();
which is less efficient because the StringBuilder
is backed by a char[]
(over-allocated by StringBuilder()
to 16
), only for that array to be defensively copied by the resulting String
.
(这是效率较低的,因为StringBuilder
由char[]
(由StringBuilder()
过度分配到16
)支持,只有由生成的String
防御性地复制该String
。)
String.valueOf(char)
"gets in the back door" by wrapping the char
in a single-element array and passing it to the package private constructor String(char[], boolean)
, which avoids the array copy.
(String.valueOf(char)
通过将char
包装在单个元素数组中并将其传递给包私有构造函数String(char[], boolean)
来“获取后门”,这避免了数组副本。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…