Most efficient way to convert java.lang.Long to primitive int
Solution 1
The Long
class has an .intValue()
method, I guess this is what you are looking for...
(warning, you may lose precision etc etc -- but you probably know that already)
Solution 2
Try this
int x = myLong.intValue( );
IAmYourFaja
my father is a principal at burgoyne intnl and got me this job programming lisp and development. I aspire to unittesting with a concentration in mobile platforms.
Updated on August 01, 2022Comments
-
IAmYourFaja almost 2 years
I have a weird scenario where I need to convert several million
java.lang.Long
s into primitiveint
types. I need to do this several times a day, every single day. Normally, I wouldn't worry about this kind of simple casting, but since it's happening so much, so often, I have to ask: what's the most efficient way to do this, and why?My first attempt:
Long myLong = getLong(); int x = Integer.valueOf(myLong.toString())
Although this seems like going 3 sides around the barn. Thanks in advance.
-
MrSmith42 over 11 yearsWARNING: Value of
Long
may not fit in anint
-
Dave Newton over 11 yearsJust use
intValue()
, and recognize you'll lose data unless your longs are restricted. -
MrSmith42 over 11 yearsDo not convert
Long
toString
and tha parse it to get anint
. -
MrSmith42 over 11 yearsIf your values fit in an
int
, replace yourLong
variables byInteger
-
Alexander Pogrebnyak over 11 yearsWhy -1? Problem is well defined and code sample is given.
-
-
Anand almost 8 yearsI am getting the error: Cannot invoke intValue() on the primitive type long
-
Alexander Pogrebnyak almost 8 years@Anand.
myLong
has to be declared asLong
notlong
. For latter case just cast it, i.e.(int) myPrimitiveLong
.