Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top