FindBugs扫描出的问题:
RV: Bad attempt to compute absolute value of signed random integer (RV_ABSOLUTE_VALUE_OF_RANDOM_INT)
This code generates a random signed integer and then computes the absolute value of that random integer. If the number returned by the random number generator is Integer.MIN_VALUE
, then the result will be negative as well (since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
). (Same problem arised for long values as well).
问题代码:
Random rd = new Random(); Math.abs(rd.nextInt());
解决办法:
使用random.nextInt(Integer.MAX_VALUE)获取从0到MAX_VALUE的数字-1
修改后代码:
Random rd = new Random(); Math.abs(rd.nextInt(Integer.MAX_VALUE));