What's the most idiomatic way in Java to verify that a cast from long
to int
does not lose any information?
This is my current implementation:
public static int safeLongToInt(long l) {
int i = (int)l;
if ((long)i != l) {
throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
}
return i;
}
DONT: This is not a solution!
My first approach was:
But that merely just casts the long to an int, potentially creating new
Long
instances or retrieving them from the Long pool.The drawbacks
Long.valueOf
creates a newLong
instance if the number is not withinLong
's pool range [-128, 127].The
intValue
implementation does nothing more than:So this can be considered even worse than just casting the
long
toint
.but Long can not exceed the maximum :)
A new method has been added with Java 8 to do just that.
Will throw an
ArithmeticException
in case of overflow.See:
Math.toIntExact(long)
Several other overflow safe methods have been added to Java 8. They end with exact.
Examples:
Math.incrementExact(long)
Math.subtractExact(long, long)
Math.decrementExact(long)
Math.negateExact(long),
Math.subtractExact(int, int)
I claim that the obvious way to see whether casting a value changed the value would be to cast and check the result. I would, however, remove the unnecessary cast when comparing. I'm also not too keen on one letter variable names (exception
x
andy
, but not when they mean row and column (sometimes respectively)).However, really I would want to avoid this conversion if at all possible. Obviously sometimes it's not possible, but in those cases
IllegalArgumentException
is almost certainly the wrong exception to be throwing as far as client code is concerned.