hash值为负_数值类型自动提升的例子&hashcode为负数

本文探讨了Java中的数值类型提升,特别是在使用Math.abs方法时遇到的特殊情况,例如Byte和Short类型的自动提升至Int类型。同时,文章指出了Integer.MIN_VALUE作为hash值时可能带来的问题,特别是在分布式环境的分区、队列选择和线程选择场景中,可能导致计算错误。解决方案是确保使用Math.abs后的结果不为负,避免模运算产生负数。
摘要由CSDN通过智能技术生成

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 int value, the result is that same value, which is negative. 就是最小的负数会abs后还是最小整数(4字节整数)

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));

}

}

3 是在形参传递到方法后,还是在参与运算时进行的自动提升? 验证下:

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~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值