gpt4 book ai didi

kotlin - Kotlin中的引用平等

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

在教程示例中,我正在学习Kotlin:

fun main() {
val a: Int = 100
val boxedA: Int? = a
val anotherBoxedA: Int? = a

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

println(boxedA === anotherBoxedA) // true
println(boxedB === anotherBoxedB) // false
}
为什么两个比较的结果不同?

最佳答案

最可能是因为Integer.valueOf的JDK实现
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(int)

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.


如果您在Intellij中反编译该方法,则会发现
   public static final void main() {
int a = 100;
Integer boxedA = Integer.valueOf(a);
Integer anotherBoxedA = Integer.valueOf(a);
int b = 1000;
Integer boxedB = Integer.valueOf(b);
Integer anotherBoxedB = Integer.valueOf(b);
boolean var6 = boxedA == anotherBoxedA;
boolean var7 = false;
System.out.println(var6);
var6 = boxedB == anotherBoxedB;
var7 = false;
System.out.println(var6);
}

关于kotlin - Kotlin中的引用平等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63613583/

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