Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 694
makoshichi Avatar asked Mar 16 '11 14:03

makoshichi


2 Answers

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.

like image 103
Aaron Digulla Avatar answered Oct 31 '22 09:10

Aaron Digulla


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;
like image 25
Andy Thomas Avatar answered Oct 31 '22 09:10

Andy Thomas