I'm trying to do a code review for our project using FindBugs.
we have a method to generate unique id (randomly) :
public static String generateUUID(int base){
return String.valueOf(getCurrentTimeInNanos((long)base)) +
String.valueOf(Math.abs(random.nextInt()));
}
and findBugs indicates RV_ABSOLUTE_VALUE_OF_RANDOM_INT
warning (RV: Bad attempt to compute absolute value of signed 32-bit random integer ) , i guess the problem is in String.valueOf(Math.abs(random.nextInt())
.
Does anyone have an explanation for why is this and how to fix it ?
Maybe it is because Math.abs can actually return negative results for integer inputs:
assertTrue( Math.abs(Integer.MIN_VALUE) < 0 );
It only does this for MIN_VALUE, though, because -MIN_VALUE cannot be represented. Kind of an overflow problem.
As for how to fix it:
don't make your own UUID. Use java.util.UUID.
cast the random number to long before calling Math.abs
use random.nextInt(Integer.MAX_VALUE) to get a number from 0 to MAX_VALUE - 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With