gpt4 book ai didi

Kotlin数字拳击测试奇怪

转载 作者:行者123 更新时间:2023-12-02 13:06:37 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





kotlin int boxed identity

(1 个回答)


4年前关闭。




我是 kotlin 的初学者。

我不明白下面的输出。

@Test
fun testNumberBoxing() {

val a:Int = 1000
val boxedA1: Int? = a
val boxedA2: Int? = a

println("first check = ${boxedA1 === boxedA2}")

val b: Int = 2
val boxedB1: Int? = b
val boxedB2: Int? = b

println("second check = ${boxedB1 === boxedB2}")
}

结果是
first check = true
second check = false

为什么两个输出不同?

我的 kotlin 版本是 1.2.31
org.jetbrains.kotlin:kotlin-stdlib-jre7:1.2.31

最佳答案

我得到的输出

first check = false
second check = true

代码编译成什么
public static final void main(@NotNull String[] args) {
Intrinsics.checkParameterIsNotNull(args, "args");
int a = 1000;
Integer boxedA1 = Integer.valueOf(a);
Integer boxedA2 = Integer.valueOf(a);
String var4 = "first check = " + (boxedA1 == boxedA2);
System.out.println(var4);
int b = 2;
Integer boxedB1 = Integer.valueOf(b);
Integer boxedB2 = Integer.valueOf(b);
String var7 = "second check = " + (boxedB1 == boxedB2);
System.out.println(var7);
}

为什么 valueOf 不一致

为此,我们需要查看 valueOf 的 JavaDoc:

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.



如您所见,对于较小的值,它将在两个调用中返回相同的对象,因此它们是相等的,而对于较大的未缓存值,这两个对象是不同的

在 java 中 == 检查对象是否相等,因此 2 个相等的对象为 false,而同一对象的 2 个副本返回 true。

关于Kotlin数字拳击测试奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49738117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com