kotlin int盒装身份

时间:2016-12-04 23:07:57

标签: int kotlin identity

在我们的文档中

  

请注意,数字装箱不会保留身份

但下一个例子会给出不同的结果

val number1 = 127
val b1 : Int? = number1
val b2 : Int? = number1
print(b1 === b2) // this prints true

val number2 = 128
val c1 : Int? = number2
val c2 : Int? = number2
print(c1 === c2) // this prints false

大于127的数字按预期工作但不高于128(8位),为什么?

1 个答案:

答案 0 :(得分:10)

本文解释了它:http://javapapers.com/java/java-integer-cache/

基本思想是Java标准库对-128和127之间的值使用缓存,因此它们总是引用相同的Integer对象(通过标识)。