简体   繁体   English

java中的(char)temp和Character.toChars(temp)和String.valueOf(Character.toChars(temp))有什么区别

[英]what is the difference between (char)temp and Character.toChars(temp) and String.valueOf(Character.toChars(temp)) in java

I got the same result from these, what is the difference? 从这些我得到了相同的结果,有什么区别? which is better? 哪个更好? temp is an int, read from reader.read() temp是一个整数,从reader.read()读取

System.out.print((char)temp);

System.out.print(Character.toChars(temp));

System.out.print(String.valueOf(Character.toChars(temp)));

The first two are basically the same, except you are calling the Character object instead of the primitive data type char. 前两个基本相同,除了您要调用Character对象而不是原始数据类型char。 The third one is just another step which is not needed, System.out.print turns the input into a readable output string anyways, so there is no need to parse the char into a string. 第三步只是不需要的另一步骤,无论如何System.out.print都会将输入转换为可读的输出字符串,因此无需将char解析为字符串。

The first way is a perfectly fine way of doing what you need done. 第一种方法是完成所需工作的完美方法。

Normally, these three statements all do the same thing. 通常,这三个语句都做相同的事情。 And certainly, this is the case if temp contains a character that you have just read using Reader.read() and that character was not a UTF-16 surrogate character. 当然,如果temp包含您刚刚使用Reader.read()读取的字符,并且该字符不是UTF-16替代字符,就属于这种情况。 (Whether this does the "right" thing or not depends on whether the default character encoding supports the character that you are trying to write.) (是否执行“正确”操作取决于默认字符编码是否支持您尝试编写的字符。)

If temp contained a Unicode codepoint that was larger than 65535 , then the first statement would end up mangling the codepoint, but the second and third statements would result in the correct representation of the character being output ... modulo the default character set issue. 如果temp包含一个大于65535的Unicode代码点,则第一条语句最终将破坏该代码点,但是第二条和第三条语句将导致输出正确的字符表示形式...以默认字符集问题为模。

If temp contained a UTF-16 surrogate character, then I'm not quite sure what would happen. 如果temp包含UTF-16代理字符,那么我不太确定会发生什么。 I suspect that it would work. 我怀疑它会起作用。 However, a literal reading of the javadoc for PrintStream.print(char) leaves open the possibility that even a UTF-16 to UTF-8 conversion might treat a single surrogate character as an error. 但是,对PrintStream.print(char)的javadoc进行字面读取可能会使即使UTF-16到UTF-8的转换也可能会将单个代理字符视为错误。 However, this is moot unless your Reader was reading as stream that included Unicode codepoints larger than 65535 . 但是,除非您的阅读器将流作为包含大于65535 Unicode代码点的流进行读取,否则这没有什么意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM