为什么在 Java 中不可能将 Wrapper Integer 转换为 Float

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17281919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:35:02  来源:igfitidea点击:

Why is Wrapper Integer to Float conversion not possible in java

javatype-conversionwrapper

提问by Ankit Zalani

Why the typecasting of Wrapper Float does not works in java for Wrapper Integer type.

为什么 Wrapper Float 的类型转换在 Java 中不适用于 Wrapper Integer 类型。

public class Conversion {
    public static void main(String[] args) {
        Integer i = 234;

        Float b = (Float)i;

        System.out.println(b);

    }
}

回答by rgettman

An Integeris not a Float. With objects, the cast would work if Integersubclassed Float, but it does not.

AnInteger不是Float。对于对象,如果Integersubclassed ,则演员表会起作用Float,但它不会。

Java will not auto-unbox an Integerinto an int, cast to a float, then auto-box to a Floatwhen the only code to trigger this desired behavior is a (Float)cast.

当触发此所需行为的唯一代码是强制Integer转换时int,Java 不会将 an 自动拆箱为 an ,转换为 a float,然后自动装箱为 a 。Float(Float)

Interestingly, this seems to work:

有趣的是,这似乎有效:

Float b = (float)i;

Java will auto-unbox iinto an int, then there is the explicit cast to float(a widening primitive conversion, JLS 5.1.2), then assignment conversion auto-boxes it to a Float.

Java 将自动拆箱iint,然后显式转换float扩展原始转换,JLS 5.1.2),然后赋值转换将其自动装箱为Float

回答by MK.

You are asking it to do too much. You want it to unbox i, cast to float and then box it. The compiler can't guess that unboxing i would help it. If, however, you replace (Float) cast with (float) cast it will guess that i needs to be unboxed to be cast to float and will then happily autobox it to Float.

你要求它做的太多了。您希望它取消装箱 i,转换为浮动,然后装箱。编译器无法猜测拆箱我会帮助它。但是,如果您将 (Float) cast 替换为 (float) cast 它会猜测我需要拆箱才能转换为浮动,然后很乐意将其自动装箱为浮动。

回答by Fritz

Wrappers are there to "objectify"the related primitive types. This sort of casting is done on the "object-level"to put it in a way, and not the actual value of the wrapped primitive type.

包装器用于“对象化”相关的原始类型。这种类型的转换是在“对象级别”上完成的,以某种方式进行,而不是包装原始类型的实际值。

Since there's no relation between Floatand Integerper se (they're related to Numberbut they're just siblings) a cast can't be done directly.

由于FloatInteger本身之间没有关系(他们有关系Number但他们只是兄弟姐妹),因此无法直接进行演员表。

回答by Raghavenda Bhat

public class Conversion {
public static void main(String[] args) {
    Integer i = 234;

    Float b = i.floatValue();

    System.out.println(b);

}}

回答by James

You could rewrite your class to work like you want:

你可以重写你的类来像你想要的那样工作:

public class Conversion {

     public Float intToFloat(Integer i) {
          return (Float) i.floatValue();
     }

}