在-128到127之间的值上Int的Kotlin引用相等行为 [英] Kotlin referential equality behavior on Int with values between -128 to 127
问题描述
我要给自己直到12:00 AM,以学习和提高Kotlin的工作效率(希望).
I'm giving myself until 12:00AM to learn and get productive (hopefully) on kotlin.
遵循 https://kotlinlang.org/docs/kotlin-docs.pdf 我在第17页上尝试了这些代码片段.请问有人可以帮助我理解为什么===
如果-128
到127
之间的值返回true
吗?
Following https://kotlinlang.org/docs/kotlin-docs.pdf I tried these snippets on page 17. Could anyone please help me understand why ===
returns true
if a value is between -128
to 127
?
以下确实显示false
:
val a: Int = 10000
val boxedA: Int? = a // Integer@445
val anotherBoxedA: Int? = a // Integer@447 why?
print(boxedA === anotherBoxedA) // false
但是将a
更改为-128
到127
之间的任何值始终会打印true
:
However changing a
to any value between -128
to 127
always prints true
:
val a: Int = -128
val boxedA: Int? = a // Integer@445
val anotherBoxedA: Int? = a // Integer@445 why?
print(boxedA === anotherBoxedA) // true!
在我看来,如果Int
值在-128
到127
(Java字节)的范围之外,则Kotlin会在赋值时创建一个新对象,从而使引用不相等.
It seems to me if Int
value is outside the bounds of -128
to 127
(Java byte) kotlin creates a new object on assignment does making the reference not equal.
推荐答案
请参见Integer.valueOf()
的Java源代码,该代码负责对int值进行装箱. Javadoc说:
See the Java source code of Integer.valueOf()
which is reponsible for boxing int values. The javadoc says:
此方法将始终缓存-128至127范围内的值
This method will always cache values in the range -128 to 127
因此,如果该范围内的带框整数具有相同的数值,则它们始终是同一对象.
So boxed integers in that range are always the same object if they have the same numeric value.
在Kotlin中,您应该将装箱的整数与==
而不是与===
进行比较.
In Kotlin, you should compare boxed Integers with ==
and not with ===
.
这篇关于在-128到127之间的值上Int的Kotlin引用相等行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!