9

I have a weird scenario where I need to convert several million java.lang.Longs into primitive int 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.

IAmYourFaja
  • 55,468
  • 181
  • 466
  • 756

3 Answers3

24

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)

fge
  • 119,121
  • 33
  • 254
  • 329
9

Try this

int x = myLong.intValue( );
Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121
-2

Try this

Integer i = (int) (long) b;
coder
  • 10,460
  • 17
  • 72
  • 125