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.
new Integer(int)
is slow... just less memory efficient since it can't use the -128 to 127 cache. –
Mowry valueOf
can at best be slightly slower than new
, because it has the method call overhead, one or two boolean checks and then a new
. I don't disagree at all that it's better to use valueOf
... I just don't think the reason you give for using it is entirely accurate. –
Mowry new Integer(0)
to Integer.valueOf(0)
, showing that valueOf
is faster for values in the cached range. It isn't a general performance comparison. –
Mowry 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;
© 2022 - 2024 — McMap. All rights reserved.
new Integer(int)
should not be that slow - only the final variable memory barrier may hit you, if using multiple threads. – Washboard