【问题标题】:Java: auto-unboxing combined with castingJava:自动拆箱与强制转换相结合
【发布时间】:2014-11-24 00:46:39
【问题描述】:

请帮我弄清楚为什么这不起作用。 (这不是实际问题,是 OCPJP 考试的心理练习。)

public class ImplicitConversions {

Integer iBoxed;
short sPrimitive = (short)iBoxed;

}

//编译器错误:不兼容的类型;必需:短,找到:整数

我假设编译器首先尝试在没有(或之前)拆箱的情况下进行强制转换,而例如算术运算 (iBoxed+iBoxed) 将首先对其进行拆箱。因此,是否可以肯定地说自动装箱/拆箱在操作顺序(一元、算术、关系、逻辑、条件、赋值)中占有一席之地,具体在哪里?

我一直在阅读下面的源代码中的转换转换(以确保我与 1.6 兼容),但这一点让我望而却步。谢谢。 http://docs.oracle.com/javase/specs/jls/se5.0/html/conversions.html#20232

【问题讨论】:

  • 您正在转换为抢占式数据类型,这是不允许的
  • @MuhammadRamahy 这应该如何工作? Integer和Short之间没有继承关系。 short sPrimitive = (Short) iBoxed; 甚至不会编译,而short sPrimitive = (Short) (Object) iBoxed; 确实编译,编译器的类型检查被规避是没有好处的。将引发运行时异常。
  • 你是对的。我不知道我为什么这么说。

标签: java casting autoboxing


【解决方案1】:

这个

(short)iBoxed

是一个独立的表达式,不依赖于其上下文。您要做的是将Integer 参考值转换为short 原始值。 That's just not a casting context that is allowed.(见本章后面的表格。)

【讨论】:

    【解决方案2】:

    Integer 有一个方法shortValue()。改用这个:

    short sPrimitive = iBoxed.shortValue();
    

    【讨论】:

      【解决方案3】:

      自动装箱/拆箱表达式不能与更宽或更窄范围的强制转换组合。

      但是,您可以双重转换 iBoxed 变量:

      short sPrimitive = (short) (int) iBoxed;
      

      首先将iBoxed 变量自动拆箱为int,然后将int 转换为short。

      【讨论】:

      • 整数 integerWrapper = 1; long i3 = (long) integerWrapper; // 好的!长 i4 = 整数包装器; // 好的
      猜你喜欢
      • 2016-06-27
      • 2023-04-06
      • 2012-03-11
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多