<分区>
为什么我们不能将 char
值作为参数传递给任何接受 short
参数的方法,而我们可以传递 char
将值传递给另一个参数为 int
类型的方法?为什么在大小相等的情况下,不会从 char
到 short
进行类型转换?我希望 short 也可以像 short
一样存储尽可能多的值。
<分区>
为什么我们不能将 char
值作为参数传递给任何接受 short
参数的方法,而我们可以传递 char
将值传递给另一个参数为 int
类型的方法?为什么在大小相等的情况下,不会从 char
到 short
进行类型转换?我希望 short 也可以像 short
一样存储尽可能多的值。
最佳答案
Why can we not pass a
char
value as a argument to any method that accepts ashort
parameter
因为在调用上下文中没有从 char
到 short
的隐式转换。
whereas we can pass a
char
value to another method whose parameter is ofint
type?
那是因为在调用上下文中有从 char
到 int
的隐式转换可用。
Why does type casting not take place from
char
toshort
, given that the sizes are equal? I hope short can also store as much values asshort
can.
尽管 char
和 short
的大小相同,但是 char
是无符号的,而 short
已签名。这就是为什么没有从 char
到 short
的隐式转换。
从char
到int
的转换是一个加宽 原语转换(JLS 5.1.2),而从char
的转换code> 到 short
是一个narrowing 原语转换 ( JLS 5.1.3 )。特别是(强调我的):
A narrowing conversion of a char to an integral type T likewise simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the resulting value to be a negative number, even though chars represent 16-bit unsigned integer values.
关于java - Java 中从 char 到 short 的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45352541/