Most efficient way to convert java.lang.Long to primitive int

30,674

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( );
Share:
30,674
IAmYourFaja
Author by

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, 2022

Comments

  • IAmYourFaja
    IAmYourFaja almost 2 years

    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.

    • MrSmith42
      MrSmith42 over 11 years
      WARNING: Value of Long may not fit in an int
    • Dave Newton
      Dave Newton over 11 years
      Just use intValue(), and recognize you'll lose data unless your longs are restricted.
    • MrSmith42
      MrSmith42 over 11 years
      Do not convert Long to String and tha parse it to get an int.
    • MrSmith42
      MrSmith42 over 11 years
      If your values fit in an int, replace your Long variables by Integer
    • Alexander Pogrebnyak
      Alexander Pogrebnyak over 11 years
      Why -1? Problem is well defined and code sample is given.
  • Anand
    Anand almost 8 years
    I am getting the error: Cannot invoke intValue() on the primitive type long
  • Alexander Pogrebnyak
    Alexander Pogrebnyak almost 8 years
    @Anand. myLong has to be declared as Long not long. For latter case just cast it, i.e. (int) myPrimitiveLong.