Convert Long into Integer

后端 未结 14 2084
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 07:48

How to convert a Long value into an Integer value in Java?

相关标签:
14条回答
  • 2020-12-07 07:55

    Assuming not null longVal

    Integer intVal = ((Number)longVal).intValue();
    

    It works for example y you get an Object that can be an Integer or a Long. I know that is ugly, but it happens...

    0 讨论(0)
  • 2020-12-07 07:56

    Here are three ways to do it:

    Long l = 123L;
    Integer correctButComplicated = Integer.valueOf(l.intValue());
    Integer withBoxing = l.intValue();
    Integer terrible = (int) (long) l;
    

    All three versions generate almost identical byte code:

     0  ldc2_w <Long 123> [17]
     3  invokestatic java.lang.Long.valueOf(long) : java.lang.Long [19]
     6  astore_1 [l]
     // first
     7  aload_1 [l]
     8  invokevirtual java.lang.Long.intValue() : int [25]
    11  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
    14  astore_2 [correctButComplicated]
    // second
    15  aload_1 [l]
    16  invokevirtual java.lang.Long.intValue() : int [25]
    19  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
    22  astore_3 [withBoxing]
    // third
    23  aload_1 [l]
    // here's the difference:
    24  invokevirtual java.lang.Long.longValue() : long [34]
    27  l2i
    28  invokestatic java.lang.Integer.valueOf(int) : java.lang.Integer [29]
    31  astore 4 [terrible]
    
    0 讨论(0)
  • 2020-12-07 07:56

    For non-null values:

    Integer intValue = myLong.intValue();
    
    0 讨论(0)
  • 2020-12-07 07:57

    try this:

    Int i = Long.valueOf(L)// L: Long Value

    0 讨论(0)
  • 2020-12-07 07:58

    Using toIntExact(long value) returns the value of the long argument, throwing an exception if the value overflows an int. it will work only API level 24 or above.

    int id = Math.toIntExact(longId);
    
    0 讨论(0)
  • 2020-12-07 07:59

    long visitors =1000;

    int convVisitors =(int)visitors;

    0 讨论(0)
提交回复
热议问题