new Integer(1) 返回与 1 不同的标识符

huangapple go评论71阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年9月9日 23:23:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63814782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定