在Integer class,有private static class IntegerCache.
这门课有什么用?
使用时如何受益Integer?
我是java的新手.我对包装类和原始数据类型有所了解,但我遇到的是令人惊讶的.在将变量i和j的值从1000更改为100时,输出将从false更改为true.我需要知道这背后的机制.
class Demo{
public static void main(String[] args){
Integer i=1000,j=1000;
if(i==j)
System.out.println("true");
else
System.out.println("false");
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码给了我"假",而..
class Demo{
public static void main(String[] args){
Integer i=100,j=100;
if(i==j)
System.out.println("true");
else
System.out.println("false");
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码给我"真实"
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
Run Code Online (Sandbox Code Playgroud)
boexA === andotherBoxedA我不明白的是和之间有什么区别boexB === andotherBoxedB
更令人困惑的是,当更改 b t0 100 时,输出为 true true
val a: Int = 100
val boxedA: Int? = a
val anotherBoxedA: Int? = a
val b: Int = 100
val boxedB: Int? = b
val …Run Code Online (Sandbox Code Playgroud) 根据Java语言规范第5.1.7节,Java将-c8 Integer从-128 缓存到127以进行性能优化.
因此,当您a == b与缓存范围中的a&bIntegers 进行比较时,即使它们是不同的对象,它也会返回true.
从机制上讲,这种缓存带来了哪些性能优势?根据这个答案,"目的主要是为了节省内存,由于更好的缓存效率,这也可以带来更快的代码." 它如何导致更快的代码?我如何使用此功能来提高我编写的实际代码的性能?
它与类中的以下方法有什么关系IntegerCache吗?
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Run Code Online (Sandbox Code Playgroud) 我想在我的应用程序中检查Integer相等,但遇到了一个奇怪的行为.在某些时候我的应用程序正常工作,但在某些时候它失败了.所以我在这里写了一个测试代码
public class EqualityTest {
public static void main(String args[]) {
Integer a = 100;
Integer b = 100;
Integer c = 1000;
Integer d = 1000;
if (a == b) {
System.out.println("a & b are Equal");
}
else {
System.out.println("a & b are Not Equal");
}
if (c == d) {
System.out.println("c & d are Equal");
} else {
System.out.println("c & d are Not Equal");
}
}
}
Run Code Online (Sandbox Code Playgroud)
产量
a & b are Equal
c & d are Not …Run Code Online (Sandbox Code Playgroud) 在jvm imgui中,我正在使用
System.identityHashCode(i++)
哪里
var i = 0
为每个帧始终为给定对象生成一个常数id(因此
可以对其进行跟踪)
但是,一个用户案例只是告诉我,这仅对中的值有效[0, 125]
尝试调试并查找错误,我结束了这段简短的代码测试:
var i = 0
val A = Array(256, { System.identityHashCode(i++) })
i = 0
val B = Array(256, { System.identityHashCode(i++) })
repeat(256) {
if (A[it] != B[it])
println("[$it] different, A ${A[it]}, B ${B[it]}")
}
Run Code Online (Sandbox Code Playgroud)
还有:
这是为什么?
我是否可以安全地假设这种行为在其他平台上也能保持一致?
我想知道:为什么这个代码导致了false?当
Coz ==运算符true是相同的存储点时,它应该返回.
public static void main(String[] args) {
String a = new String("hello");
System.out.println(a == "hello");
}
Run Code Online (Sandbox Code Playgroud)
java ×6
kotlin ×2
autoboxing ×1
caching ×1
equality ×1
hashcode ×1
integer ×1
performance ×1
primitive ×1
wrapper ×1