为什么将 short 变量分配给 Integer 引用会产生编译时错误? [英] Why does the assignment of a short variable to an Integer reference produce a compile time error?

查看:31
本文介绍了为什么将 short 变量分配给 Integer 引用会产生编译时错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Java 中有以下代码:

I have the following code in Java :

class Boxing
    {
        public static void main(String args[])
        {
            short s = 10;
            Integer iRef = s;
        }
    }

为什么编译会报错?如果我在表达式中显式地将 short 类型转换为整数,它将成功编译.由于我在表达式中使用 short 类型不是默认情况下应该是整数而不需要显式大小写的类型吗?

Why does it produce an error in compilation? If I explicitly typecast the short to an integer in the expression, it compiles successfully. Since I'm using a short in an expression isn't the type of that supposed to be an integer by default without requiring the explicit case?

推荐答案

您希望这里发生两件事:加宽和自动装箱.

You want to have two things happening here: widening and auto-boxing.

不幸的是,Java 只会自动执行这两项中的一项.其原因很可能是自动装箱引入的很晚(在 Java5 中),他们必须小心不要破坏现有代码.

Unfortunately, Java does only one of the two automatically. The reason for that is most likely that autoboxing was introduced fairly late (in Java5), and they had to be careful to not break existing code.

你可以做到

int is = s;    // widening

Short sRef = s;   // autoboxing

Integer iRef = (int) s;  // explicit widening, then autoboxing

这篇关于为什么将 short 变量分配给 Integer 引用会产生编译时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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