kotlin int盒装身份

在我们的文档中

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

但接下来的例子给出了不同的结果

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位)以上时,为什么?

这篇文章解释它: http : //javapapers.com/java/java-integer-cache/

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

Interesting Posts