findbug 發現的一些隱藏問題總結

RV_ABSOLUTE_VALUE_OF_RANDOM_INT 使用錯誤 - 嘗試計算32位隨機整數的絕對值

Math.abs(System.currentTimeMillis())

說明: Math.abs 不必定返回的數據是正數,下面是個例子:dom

System.out.println(Math.abs(Long.MIN_VALUE));

這個執行的結果是: -9223372036854775808ide

解釋: Consider a byte. Its value ranges from -128 to 127. Say your byte has a value of -100, then Math.abs(-100) will give you 100. But what if the value of your byte is -128? You cannot represent 128 as a byte, since the maximum value it can represent is 127. So Math.abs() simply returns the negative parameter, unchanged.code

解決辦法:get

Use 
    rand.nextInt(Integer.MAX_VALUE);
instead of 
    Math.abs(rand.nextInt())

參考地址: http://stackoverflow.com/questions/23435875/how-to-compute-absolute-value-of-signed-random-integerit

相關文章
相關標籤/搜索