답변:
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);
intValue대신 전화 할 수 있는데 왜 두 번이나 캐스팅 하시겠습니까? 게다가 그것은 unbox to long, cast to int 및 rebox to로 갈 Integer것입니다. 매우 유용하지는 않습니다. 나는 머리 꼭대기에 요점이 보이지 않습니다. 이것에 대한 충분한 이유가 있습니까?
Long에 long처음 다음에int
다음과 같은 세 가지 방법이 있습니다.
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]
123L가독성을 위해 대문자 접미사 를 사용해야합니다 .
널이 아닌 값의 경우 :
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;
}
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);
}
}
Java 8에서는을 사용할 수 있습니다 toIntExact. null값 을 처리 하려면 다음을 사용하십시오.
Integer intVal = longVal == null ? null : Math.toIntExact(longVal);
이 메소드의 좋은 점은 ArithmeticException인수 ( long)가을 오버플로하는 경우 if를 던진다는 것 int입니다.
자바에서는 long을 int로 변환하는 엄격한 방법이 있습니다.
lnog는 int로 변환 할 수있을뿐만 아니라 모든 유형의 클래스 확장 Number는 일반적으로 다른 Number 유형으로 변환 할 수 있습니다. 여기서 long을 int로 변환하는 방법을 보여 주며 다른 유형도 그 반대로 변환합니다.
Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);