【问题标题】:Why does the char type not feature on Java's "widening path"?为什么 char 类型没有出现在 Java 的“拓宽路径”中?
【发布时间】:2014-03-25 09:26:11
【问题描述】:

我知道Java的自动类型转换可以用一种叫做“拓宽路径”的东西来概括,它看起来像这样:

byte -> short -> int -> long -> float -> double

以下代码编译正常,并说明了一些 char/int 转换:

char c = '1';
int i = c;  // char to int

// char to int, and vice versa
switch (c) {
    case 1:
}
switch (i) {
    case '1':
}

鉴于上述所需的转换,为什么 char 类型没有出现在 Java 的拓宽路径上?谢谢。

【问题讨论】:

  • 部分原因是char 是无符号的,因此在某种意义上比short 更窄。

标签: java type-conversion


【解决方案1】:

charint 当然是扩大转换。但是intchar 不是,因为您似乎是根据第二个switch 声明来思考的。在那里,它实际上是case 中的'1' char 类型,它根据它的unicode 代码点转换为int 类型。此外,JLS §5.1.2 - Widening Primitive conversion 明确指出从charint 的转换正在扩大。

【讨论】:

  • 谢谢。我一定是从某个地方复制并粘贴了“byte -> short -> int -> long -> float -> double”行,认为这是扩大的正确规则。
  • @user2911290 实际上,在复制粘贴时,您错过了必须从char -> int 平行于byte -> short -> int 的转换。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多