[java] Long을 정수로 변환

Java에서 Long값을 값으로 변환하는 방법은 Integer무엇입니까?



답변

Integer i = theLong != null ? theLong.intValue() : null;

또는 null에 대해 걱정할 필요가없는 경우 :

// auto-unboxing does not go from Long to int directly, so
Integer i = (int) (long) theLong;

두 경우 모두 Long은 정수보다 넓은 범위를 저장할 수 있기 때문에 오버플로가 발생할 수 있습니다.

Java 8에는 오버플로를 검사하는 도우미 메서드가 있습니다 (이 경우 예외가 발생 함).

Integer i = theLong == null ? null : Math.toIntExact(theLong);


답변

다음과 같은 세 가지 방법이 있습니다.

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

세 버전 모두 거의 동일한 바이트 코드를 생성합니다.

 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]


답변

널이 아닌 값의 경우 :

Integer intValue = myLong.intValue();


답변

오버플로를 확인하고 Guava를 편리하게 사용하려면 다음이 있습니다 Ints.checkedCast().

int theInt = Ints.checkedCast(theLong);

구현 은 간단하고 오버플로에서 IllegalArgumentException 을 발생시킵니다.

public static int checkedCast(long value) {
  int result = (int) value;
  checkArgument(result == value, "Out of range: %s", value);
  return result;
}


답변

캐스트를 입력해야합니다.

long i = 100L;
int k = (int) i;

long은 int보다 큰 범위를 가지므로 데이터가 손실 될 수 있습니다.

박스형에 대해 이야기하고 있다면 설명서 를 읽으십시오 .


답변

Java 8을 사용하는 경우 다음과 같이하십시오.

    import static java.lang.Math.toIntExact;

    public class DateFormatSampleCode {
        public static void main(String[] args) {
            long longValue = 1223321L;
            int longTointValue = toIntExact(longValue);
            System.out.println(longTointValue);

        }
}


답변

가장 간단한 방법은 다음과 같습니다.

public static int safeLongToInt( long longNumber )
    {
        if ( longNumber < Integer.MIN_VALUE || longNumber > Integer.MAX_VALUE )
        {
            throw new IllegalArgumentException( longNumber + " cannot be cast to int without changing its value." );
        }
        return (int) longNumber;
    }