Safely casting long to int in Java -
What is the most idiomatic method in Java to ensure that is long
to int
Do not lose any information?
This is my current implementation:
Public Static Int Safe Longtoint (long) {int i = (int) l; If ((long) I! = L) {Setting new invalid records exception (L + "can not be inserted without changing its value."); } Came back; A new method was added with
Java 8 To do this
import static java.lang.Math.toIntExact; Long afu = 10 l; Int bar = toIntExact (foo);
In case of overflow, an arithmetic will throw exceptions.
See:
Some other overflow safe methods have been added to Java 8. They end with exact .
Example:
-
Math.incrementExact (long)
-
math. SubtractExact (tall, long)
-
Math. TransitionXact (long)
-
Math AngateAccact (long),
-
Math. SubtractExact (int, int)
Comments
Post a Comment