Kotlin / Java Int 类

耳语

那里

我正在关注官方网站上的 Kotlin 教程,并且对以下示例中的结果感到非常困惑:

fun main() {
    val a: Int = 100
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a

    val b: Int = -129
    val boxedB: Int? = b
    val anotherBoxedB: Int? = b

    val c: Int = -128
    val boxedC: Int? = c
    val anotherBoxedC: Int? = c

    val d: Int = 127
    val boxedD: Int? = d
    val anotherBoxedD: Int? = d
    
    val e: Int = 128
    val boxedE: Int? = e
    val anotherBoxedE: Int? = e
    
    println(boxedA === anotherBoxedA) // true
    println(boxedB === anotherBoxedB) // false
    println(boxedC === anotherBoxedC) // true
    println(boxedD === anotherBoxedD) // true
    println(boxedE === anotherBoxedE) // false
}

有人能帮忙解释一下为什么Int类似乎对数据范围 [-128, 127) 有不同的存储方法吗?

我无法从 Integer 类定义中找到任何线索。

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

提前致谢。

阿布舍克

默认情况下,Int 缓存来自 [-128,127] 的值。您可以查看以下链接以获取更多信息https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(int)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章