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;
}
long
, why can't you just work with along
? That way, you'll never have to worry about this.