英文:
new Integer(1) returns a different id with 1
问题
假设以下赋值语句:
jshell> int a = 1;
a ==> 1
jshell> int b = 1;
b ==> 1
jshell> var c = new Integer(1);
c ==> 1
使用 System.identityHashCode 检查它们的标识:
jshell> System.out.println(System.identityHashCode(1))
1938056729
jshell> System.out.println(System.identityHashCode(a))
1938056729
jshell> System.out.println(System.identityHashCode(b))
1938056729
jshell> System.out.println(System.identityHashCode(c))
343965883
C 返回了一个不同的标识,c 引用的 "1" 与 a 和 b 的不同吗?
英文:
Suppose the following assignment:
jshell> int a = 1;
a ==> 1
jshell> int b = 1;
b ==> 1
jshell> var c = new Integer(1);
c ==> 1
Check their id with System.identityHashCode:
jshell> System.out.println(System.identityHashCode(1))
1938056729
jshell> System.out.println(System.identityHashCode(a))
1938056729
jshell> System.out.println(System.identityHashCode(b))
1938056729
jshell> System.out.println(System.identityHashCode(c))
343965883
C returns a different ID, the "1" which c references is different from that of a and b?
答案1
得分: 3
这是预期的结果。前三行是装箱转换,而且 Integer::valueOf 被指定在闭区间 -128 到 127 返回相同的实例。
你明确地使用了 new
来创建 c
的实例。这将总是创建一个新的实例,其哈希码会不同。如果你将 new Integer(1)
替换为 Integer.valueOf(1)
,它将返回与其他实例相同的哈希码。
英文:
That is expected. The first three lines are boxing conversions and Integer::valueOf is specified to return the same instances for the inclusive range -128 to 127.
You explicitly used new for c. That will always create a new instance which returns a different hash code. If you replace new Integer(1)
with Integer.valueOf(1)
it will return the same hash code as the others.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论