Integer的取值范围(跳坑demo+源码分析)

首先都知道Integer是Int的包装类型,那么理所当然的:
Integer类取值和 int 类型取值范围一样,从-2147483648 至 2147483647(-231至 231-1) ,包括-2147483648 和 2147483647。
那么再理所当然认为:在这个范围内的 比较操作符 == ,都是true。
结果就踩了坑。

(1)验证Integer的最大值与最小值范围:

Integer的取值范围(跳坑demo+源码分析)
Integer的取值范围(跳坑demo+源码分析)
21亿四千万,没错,是Int的Max Value

(2)踩坑:

Integer的取值范围(跳坑demo+源码分析)
这个值对于Max Value来说,很小,看到想都不用想,就是 true。
Integer的取值范围(跳坑demo+源码分析)

…为什么呢?点进去Integer类看源码:

Integer的取值范围(跳坑demo+源码分析)

所以,阿里规约明确规定:对于包装类型,一定一定要 .equals () 比较。才不会出现预料之外的问题

Integer的取值范围(跳坑demo+源码分析)
Integer的取值范围(跳坑demo+源码分析)

收工