扩展和装箱Java原语 [英] Widening and Boxing Java primitives

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

问题描述

对Java原语进行野生和装箱.

Widening and Boxing Java primitives.

我知道不可能将包装器类从一个扩展到另一个,因为它们不是来自同一继承树.为什么无法将原语扩展为另一种原语类型并自动装箱已扩展的原语?

I know it is not possible to widen a wrapper class from one to another as they are not from the same inheritence tree. Why though is it not possible to widen a primitive to another primitive type and autobox the widened primitive?

鉴于可以将byte参数传递给需要int的方法,为什么不能将以下示例中的字节扩展为int然后装箱为Integer?

Given that a byte argument can be passed to a method that expects an int, why cant the byte in the following example be widened to an int and then boxed to an Integer?

class ScjpTest{
    static void goInteger(Integer x){
        System.out.println("Going with an Integer");
    }

    static void goInt(int x){
        System.out.println("Going with an int");
    }

    public static void main(String args[]){
        byte b = 5;
        goInt(b);
        goInteger(b);
    }
}

在上面的示例中,goInt(b)被编译器接受,但goInteger(b)被拒绝.

In the above example, goInt(b) is accepted by the compiler but goInteger(b) is rejected.

推荐答案

简短答案

Java语言仅支持某种程度的粗心.

Short answer

The java language only supports some level of carelessness.

我相信添加了自动装箱功能以支持开发人员的粗心大意.特别是在这样的情况下:我需要一个整数作为要调用的方法的参数,但是我有一个整数.以某种方式,新的Integer(int)永远不会弹出我的脑海.相反,我只会发送一个整数Java编译器将为我执行新的Integer()调用.谢谢Java粗心支持小组!"

I believe that autoboxing was added to support developer carelessness. Specifically in situations like this: "I need an Integer as a parmeter to the method I want to call, but I have an int. Somehow, new Integer(int) never pops into my head. Instead, I'll just send an int and the java compiler will do the new Integer() call for me. Thanks java carelessness support group!"

设计自动装箱的人愿意支持1级粗心(int => Integer and back),但是不愿意支持将较小的原始类型自动转换为较大的原始类型以及自动创建和从原始类型提取包装器类.我怀疑对此的决策矩阵会比当前自动装箱方案的决策矩阵大一些.

The folks designing autoboxing were willing to support 1 level of carelessness (int => Integer and back), but were not willing to support auto casting of smaller primitive types to larger primitive types in conjunction with automatic creation and extration from primitive type wrapper classes. I suspect the descision matrix for this would be somewhat larger than the decision matrix for the current autoboxing scheme.

这篇关于扩展和装箱Java原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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