You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin与Java中Integer缓存行为差异原因探究

Kotlin与Java数值类型比较差异解析

我理解String的驻留机制,但对其他类型的类似运作机制不太清楚。比如Java中的Integer类型表现如下:

class Main {
    public static void main(String[] args) {
        Integer x = 127;
        Integer y = 127;
        System.out.println(x == y); // true
        
        Integer xx = 128;
        Integer yy = 128;
        System.out.println(xx == yy); // false
    }
}

但在Kotlin中,无论数值大小,===比较始终返回true:

fun main() {
    val x: Int = 127
    val y: Int = 127
    println(x === y) // true
    
    val xx: Int = 128
    val yy: Int = 128
    println(xx === yy) // true
    
    val xxx: Int = 128128128
    val yyy: Int = 128128128
    println(xxx === yyy) // true
}

为什么Kotlin会有这样的表现?我想了解相关信息却不知从何入手。


补充测试与结论

感谢解答后补充的测试代码:

fun main() {
    val a: Int? = 128
    val b: Int? = 128
    
    println(a === b) // false
    println(a == b) // true
    
    val aa: Int? = 127
    val bb: Int? = 127
    
    println(aa === bb) // true
    println(aa == bb) // true
}

通过测试可总结JVM平台上Kotlin数值类型的核心特性:

  • 非空数值类型(如Int、Double):
    • 底层以JVM原始类型(如int、double)存储
    • ===与==比较逻辑完全等价,均直接对比数值本身,而非对象引用
  • 可空数值类型(如Int?、Double?):
    • 底层会被装箱为对应的Java包装类(如Integer、Double)
    • ===对比包装类对象的引用地址,==对比数值本身
    • 对于-128到127范围内的整数,装箱时会复用缓存对象,因此该区间内的可空整数用===对比也会返回true

内容的提问来源于stack exchange,提问作者Greg_M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 05:12:42