"Byte" 个数字的 Kotlin 引用相等性
Kotlin reference equality for "Byte" numbers
在 Kotlin 官方参考资料中 https://kotlinlang.org/docs/reference/basic-types.html#numbers 我读到:
Note that boxing of numbers does not necessarily preserve identity
以及说明如何表示的示例:
val a: Int = 10000
print(a === a) // Prints 'true'
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
经过一些自发测试后,我意识到它对于字节数 (<128) 应该可以正常工作:
val a = 127
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) //!!!Prints 'true'!!!
也在同一参考资料中 https://kotlinlang.org/docs/reference/equality.html 我发现:
For values which are represented as primitive types at runtime (for example, Int), the === equality check is equivalent to the == check
但这并不能解释这种情况:
val a = 128
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) //!!!Prints 'false'!!!
所以我想弄清楚为什么引用相等性“===”对数字 >=128 显示 "false" 而对 <128 显示 "true"?
这来自 Integer.valueOf(int)
是如何为 JVM 实现的:
This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
因此,对于 a = 127
,恒等式 box1 === box2
始终成立,而对于所有非 byte
值,它可能不成立。
在 Kotlin 官方参考资料中 https://kotlinlang.org/docs/reference/basic-types.html#numbers 我读到:
Note that boxing of numbers does not necessarily preserve identity
以及说明如何表示的示例:
val a: Int = 10000
print(a === a) // Prints 'true'
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
经过一些自发测试后,我意识到它对于字节数 (<128) 应该可以正常工作:
val a = 127
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) //!!!Prints 'true'!!!
也在同一参考资料中 https://kotlinlang.org/docs/reference/equality.html 我发现:
For values which are represented as primitive types at runtime (for example, Int), the === equality check is equivalent to the == check
但这并不能解释这种情况:
val a = 128
val boxedA: Int? = a
val anotherBoxedA: Int? = a
print(boxedA === anotherBoxedA) //!!!Prints 'false'!!!
所以我想弄清楚为什么引用相等性“===”对数字 >=128 显示 "false" 而对 <128 显示 "true"?
这来自 Integer.valueOf(int)
是如何为 JVM 实现的:
This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
因此,对于 a = 127
,恒等式 box1 === box2
始终成立,而对于所有非 byte
值,它可能不成立。