1

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?

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • 1
    `a` and `b` are primitives. `c` is an object. Recommend searching "objects vs primitives" or something along those lines – byxor Sep 09 '20 at 15:26
  • java primitives have wrapper classes which are not the same as the pimitive types themselves – Jakob F Sep 09 '20 at 15:27
  • new Integer allocates a new Integer. [autoboxing](https://stackoverflow.com/questions/22648627/how-java-auto-boxing-unboxing-works) uses [Integer.valueOf](https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(int)), which may cache values –  Sep 09 '20 at 15:30
  • Just to be clear, since it's been implied by comments and the answer, but not stated: `a` and `b` do not have an identityHashCode, they are primitives not Objects. So they are getting autoboxed to an Integer. – matt Sep 09 '20 at 15:42

1 Answers1

3

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.

Juan C Nuno
  • 476
  • 1
  • 3
  • 8