Java杂记（八）坑：Math.abs 方法边界问题

源码及分析

Java 中 Math.abs() 返回一个数的绝对值，但是取边界值（即最大或最小值）时，可能会出现负数的情况

源码（以 int 为栗）

public static int abs(int a) {
return (a < 0) ? -a : a;
}


Returns the absolute value of an int value.
If the argument is not negative, the argument is returned.
If the argument is negative, the negation of the argument is returned.
Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.


其它数据类型特例

long

Note that if the argument is equal to the value of Long.MIN_VALUE, the most negative representable long value, the result is that same value, which is negative.


float

Special cases:
If the argument is positive zero or negative zero, the result is positive zero.
If the argument is infinite, the result is positive infinity.
If the argument is NaN, the result is NaN.
In other words, the result is the same as the value of the expression:

Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))


double

Special cases:
If the argument is positive zero or negative zero, the result is positive zero.
If the argument is infinite, the result is positive infinity.
If the argument is NaN, the result is NaN.
In other words, the result is the same as the value of the expression:

Double.longBitsToDouble((Double.doubleToLongBits(a)<<1)>>>1)


小结

Last Modified: July 5, 2018
Leave a Comment