简体   繁体   中英

Java 1.4: Cast primitive type to Object (Coupling vs Performance?)

This is actually related to a question I asked earlier, but I was left hanging on this detail. I'm restricted to Java 1.4 and I want to cast an int type to Object . Do I really need to use an Integer class object or there's a way to cast it directly (there's no auto-boxing in 1.4). Is the cost of this "manual boxing" worthwhile over importing a whole class from the 3rd layer to the 1st layer, thus increasing coupling?

There is no simple way to convert a primitive to its Object-based twin in Java 1.4 but there is a slow and a fast way. new Integer(int) is slow, Integer.valueOf(int) is fast. The same is true for all the other number types.

In Java 5, you don't need as much code but internally, the compiler will insert a call to valueOf() for you when you use autoboxing.

In your Java 1.4 environment, you cannot cast an int to an Object, because it is not an Object.

Java distinguishes between primitive types and reference types. An int is a primitive type. So are boolean, byte, char, short, long, float and double.

A value of reference type is a reference to some object. "Object" is the root class of all objects.

In Java 1.5 and afterward, autoboxing will lead the second variable to point to an Integer object holding the same value as the primitive variable i .

    int i = 99;
    Object o = (Object) i;

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