简体   繁体   中英

Why is Wrapper Integer to Float conversion not possible in java

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

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

        Float b = (Float)i;

        System.out.println(b);

    }
}

An Integer is not a Float . With objects, the cast would work if Integer subclassed Float , but it does not.

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

Interestingly, this seems to work:

Float b = (float)i;

Java will auto-unbox i into 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 .

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.

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 Float and Integer per se (they're related to Number but they're just siblings) a cast can't be done directly.

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

    Float b = i.floatValue();

    System.out.println(b);

}}

You could rewrite your class to work like you want:

public class Conversion {

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM