Java:扩大和自动装箱转换问题

标签 java type-conversion

我不明白为什么 java 不进行扩展然后自动装箱。

Integer i = (short) 10;

我认为会发生以下情况:

  1. 首先将转换从 10 缩小到 short
  2. short 将扩展为 int
  3. int 然后会自动装箱到 Integer

相反,这是一个编译错误。

示例 2:

短 x = 10;
整数 y = x;

这也失败了。

最佳答案

根据JLS, Section 5.2 ,处理赋值转换:

Assignment contexts allow the use of one of the following:

  • an identity conversion (§5.1.1)

  • a widening primitive conversion (§5.1.2)

  • a widening reference conversion (§5.1.5)

  • a boxing conversion (§5.1.7) optionally followed by a widening reference conversion

  • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.

无法同时应用两种转换(加宽图元转换和装箱转换);此处只能应用一种转换,因此它必须导致错误。

解决方案是将 short 转换回 int(转换转换),这将允许赋值转换为装箱转换:

Integer i = (int) (short) 10;

(或者在这里,首先不要将它转换为 short。)

Integer i = 10;

关于Java:扩大和自动装箱转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17935931/

相关文章:

ocaml - OCaml int转换为二进制字符串

php - 在 IF 条件下与 int 和 string 进行比较

java - 如何防止 solr 在索引时解码 url?

java - Spring 启用独立的 Java 库

java - 格式化正则表达式的问题

java - 找不到任何适用于 netbeans 的 JAX-RPC 插件

go - 包装类型的惯用方法是什么?

typescript - 无法使用 typescript 联合类型调用 Array.every()

从 32 位地址转换为 64 位整数会产生意外结果

Java 正则表达式 - 如何应用正则表达式来获取所有由 ASCII 字符括起来的字符串?