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

makoshichi picture makoshichi · Mar 16, 2011 · Viewed 19.2k times · Source

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?

Answer

Aaron Digulla picture Aaron Digulla · Mar 16, 2011

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.