近日FindBugs发现了一个没见过的BUG:
1 2 3 4 5 6 7 |
Bug: Bad attempt to compute absolute value of signed random integer in com.example.common.helper.SequenceHelper.getSequence(String, String) 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). Rank: Scary (7), confidence: High Pattern: RV_ABSOLUTE_VALUE_OF_RANDOM_INT Type: RV, Category: CORRECTNESS (Correctness) |
这段代码具体是:
原因是: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 arises for long values as well).
解决方案应该是将:
1 |
Math.abs(secureRandom.nextInt()) |
换为:
1 |
secureRandom.nextInt(Integer.MAX_VALUE) |
因为:
1 2 |
int java.util.Random.nextInt(int bound) Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence |
转载时请保留出处,违法转载追究到底:进城务工人员小梅 » Bad attempt to compute absolute value of signed random integer