Java:加宽和自动装箱转换问题 [英] Java: Widening and autoboxing conversion issue

查看:32
本文介绍了Java:加宽和自动装箱转换问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么 java 不进行加宽然后自动装箱.

I don't get why java doesn't do the widening and then autoboxing.

Integer i = (short) 10;

我认为会发生以下情况:

I would think the following would take place:

  1. 首先将转换范围从 10 缩小到 short.
  2. short 然后会扩展为 int.
  3. int 然后会自动装箱为 Integer.
  1. Narrowing conversion first from 10 to short.
  2. short would then widen to int.
  3. int would then autobox to Integer.

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

Instead it's a compilation error.

示例 2:

短 x = 10;
整数 y = x;

Short x = 10;
Integer y = x;

这也失败了.

推荐答案

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

分配上下文允许使用以下之一:

Assignment contexts allow the use of one of the following:

  • 身份转换(第 5.1.1 节)

  • an identity conversion (§5.1.1)

扩大原始转换(第 5.1.2 节)

a widening primitive conversion (§5.1.2)

扩大参考转换(第 5.1.5 节)

a widening reference conversion (§5.1.5)

装箱转换(第 5.1.7 节),可选后跟加宽参考转换

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

拆箱转换(第 5.1.8 节),可选后跟扩展原始转换.

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

不能同时应用两次转换(拓宽基元转换和装箱转换);此处只能应用一次转换,因此必须导致错误.

It is unable to apply two conversions at once (widening primitive conversion and boxing conversion); only one conversion can apply here, so it has to result in an error.

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

The solution would be to cast the short back to an int (a casting conversion), which would allow the assignment conversion to be a boxing conversion:

Integer i = (int) (short) 10;

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

(Or here, don't cast it to short in the first place.)

Integer i = 10;

这篇关于Java:加宽和自动装箱转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆