public static int abs(int a) {
return (a < 0) ? -a : a;
}
public static long abs(long a) {
return (a < 0) ? -a : a;
}
public static float abs(float a) {
return (a <= 0.0F) ? 0.0F - a : a;
}
public static double abs(double a) {
return (a <= 0.0D) ? 0.0D - a : a;
}
以上4個方法分別返回int、long、float、double類型的絕對值,方法裏面的邏輯也簡單,無非就是整數直接返回,負數取相反數返回。
Math.abs(orderId.hashCode()) % 1024;
但是,上面這個邏輯是有問題的!!!
public static void main(String[] args) {
System.out.println(Math.abs(Integer.MIN_VALUE));
}
執行以上代碼,得到的結果是:
-2147483648
很明顯,這是個負數!!!
2147483647用二進制的補碼錶示是:
01111111 11111111 11111111 11111111
這個數 +1 得到:
10000000 00000000 00000000 00000000
這個二進制就是-2147483648的補碼。
Math.abs((long)orderId.hashCode()) % 1024;
就萬無一失了。
public static void main(String[] args) {
System.out.println(Math.abs((long)Integer.MIN_VALUE));
}
得到的結果就是:
2147483648
以上,就是今天要介紹的知識點了。
往期推薦
絕,Java 中創建對象的 5 種方法!
SpringBoot 優雅的參數效驗!
MyBatis 的執行流程,學廢了!
本文分享自微信公衆號 - Java中文社羣(javacn666)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。