1 Math类的abs方法
public static int abs(int a) {
return (a < 0) ? -a : a;
}
注意到该方法 有这样一段注释
Note that if the argument is equal to the value of Integer.MIN_VALUE
, the most negative representableint
value, the result is that same value, which is negative.
2 Byte和short类型的会自动提升至int类型,在通过传递形参时候(为什么呢?原来的类型会丢失?)
public class Main {
public static void main(String[] args) throws Exception {
Byte b = Byte.MIN_VALUE;
System.out.printf("%010x\n", b); // 0000000080
System.out.println(b); // -128
System.out.printf("%010x\n", Math.abs(b)); // 0000000080
// 自动提升至整型,再参与运算
System.out.println(Math.abs(b)); // 128
Integer i = Integer.MIN_VALUE;
System.out.printf("%010x\n", i); // 0080000000
System.out.println(i); // -2147483648
System.out.printf("%010x\n", Math.abs(i)); // 0080000000
// 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.
System.out.println(Math.abs(i)); // -2147483648
//
test();
}
// 自动提升只long类型,最小的整数Integer.MIN_VALUE,会被提升为long类型
public static long abs(long a) {
// 输入整形自动提升为长整形
return (a < 0) ? -a : a;
}
public static void test() {
// 结果是 2147483648
System.out.println(abs(Integer.MIN_VALUE));
}
}
public class Main {
public static void main(String[] args) throws Exception {
Integer i = Integer.MIN_VALUE;
System.out.printf("%010x\n", i);
System.out.println(i);
System.out.println(abs(i));
}
public static long abs(long a) {
System.out.printf("%010x\n", a);
System.out.println(a);
// 输入整形自动提升为长整形
return (a < 0) ? -a : a;
}
}
结果顺序是
0080000000
-2147483648
ffffffff80000000
-2147483648
2147483648
确定是经过形参后,进行运算前的提升
4 实践中hashcode 可能算出来的是这个最小的负数 Integer.MIN_VALUE。分布式环境计算分区、队列选择、线程选择的时候是个坑。
一般partitionSelector这样实现:
Math.abs(attribute.hashCode()) % M ;
当hash值恰好是 Integer.MIN_VALUE时,出现负数,导致bug~~~