Reputation: 22113
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?
Upvotes: 1
Views: 67
Reputation: 563
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.
Upvotes: 3