hashcode与Math.abs同时使用的隐藏坑

16 阅读1分钟

问题现象

根据业务需要,需根据key值的hashcode值进行余数取模,将其存于不同分区表,但出现了部分key无法找到对应分区表。 image.png image.png

问题原因

由于hashcode返回值为int,其范围为-2147483648(-2^31)到2147483647(2^31-1),当对应值为-2147483648 即Integer.MIN_VALUE时,会触发Math.abs的已知问题,返回值非绝对值,而是原值

image.png

解决方案

将 hashcode返回值转为long类型,避免Math.abs入参为int类型时的问题 image.png

image.png