Converting Integer to Long
Solution 1:
Simply:
Integer i = 7;
Long l = new Long(i);
Solution 2:
No, you can't cast Integer
to Long
, even though you can convert from int
to long
. For an individual value which is known to be a number and you want to get the long value, you could use:
Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp.longValue();
For arrays, it will be trickier...
Solution 3:
Integer i = 5; //example
Long l = Long.valueOf(i.longValue());
This avoids the performance hit of converting to a String. The longValue()
method in Integer is just a cast of the int value. The Long.valueOf()
method gives the vm a chance to use a cached value.
Solution 4:
Oddly enough I found that if you parse from a string it works.
int i = 0;
Long l = Long.parseLong(String.valueOf(i));
int back = Integer.parseInt(String.valueOf(l));
Win.
Solution 5:
If the Integer is not null
Integer i;
Long long = Long.valueOf(i);
i
will be automatically typecast to a long
.
Using valueOf
instead of new
allows caching of this value (if its small) by the compiler or JVM , resulting in faster code.