Kotlin拳击,无法理解其中的区别吗? [英] Kotlin boxing, Can't understand the difference?

查看:108
本文介绍了Kotlin拳击,无法理解其中的区别吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

val a: Int = 100
val boxedA: Int? = a
val anotherBoxedA: Int? = a

val b: Int = 10000
val boxedB: Int? = b
val anotherBoxedB: Int? = b

println(boxedA === anotherBoxedA) // true
println(boxedB === anotherBoxedB) // false

我不明白的是 boexA === andotherBoxedA boexB === andotherBoxedB

更令人困惑的是,当更改为b t0 100时,输出为true

and more confusion is when change b t0 100 the output is true true

val a: Int = 100
val boxedA: Int? = a
val anotherBoxedA: Int? = a

val b: Int = 100
val boxedB: Int? = b
val anotherBoxedB: Int? = b

println(boxedA === anotherBoxedA) // true
println(boxedB === anotherBoxedB) // true

所以,我需要对此代码进行解释.

so, please I need explanation for this code.

推荐答案

因此,当优化时,-128到127范围内的Integer值将被缓存,而其他任何对象都具有与缓存的值相似的值,则它将得到缓存的值(类似于字符串池)所以当val a:Int = 100然后val boxedA:Int?= a,那么这里发生的是创建一个值为100的Integer对象,那么当val anotherBoxedA:Int时呢?= a,某事创建了一个对象,但是请稍等,如果它保持相同的值100,并且该值在-128到127的范围内,则anotherBoxedA将获得与boxedA相同的引用所以当boxedA === anotherBoxedA会产生true

So, as an optimization Integer values in -128 to 127 range get cached and any other object hold similar value to a cached one it will get a reference of the cached value (similar to string pool) so when val a:Int = 100 and then val boxedA :Int? = a, so what happened here is an Integer object got created with the value 100, so when val anotherBoxedA :Int? = a, the something an object got created, but wait, if it will hold the same value which is 100 and the value is in range -128 to 127 so anotherBoxedA will get the same reference as boxedA so when boxedA === anotherBoxedA will produce true

另一方面,b = 10000,它大于缓存范围(-128:127),因此boxedB = b将创建一个新的Integer对象,anotherBoxedB = b将再次创建一个新对象,因此(boxedB === anotherBoxedB)将产生false

on the other hand b=10000 which is larger than the cache range (-128 : 127) so boxedB = b will create a new Integer object , anotherBoxedB = b will again create a new object , so (boxedB === anotherBoxedB) will produce false

这篇关于Kotlin拳击,无法理解其中的区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆