When we print new int[]{2} inside main method, We will get hashcode [I@138a55? Does int array overrides hashcode? Is it because new int[] auto boxes to be Integer[]? What's the reason?
Asked
Active
Viewed 230 times
-1
-
3Possible duplicate of [What's the simplest way to print a Java array?](http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) – Mar 14 '16 at 11:31
-
1There is no auto(un)boxing of array types. `[I@138a55` is not a hashcode but a value returned by `toString()` method, haschodes are just ints. Default implementation of `toString()` method returns `[I@74a14482` for `int[]` and `[Ljava.lang.Integer;@1540e19d` for `Integer[]`. – Jaroslaw Pawlak Mar 14 '16 at 11:32
-
@LutzHorn It is diferent context – AskQ Mar 14 '16 at 11:54
-
*"Does new int[] autoboxes to new Integer[]?"*--no, why it should? – Alex Salauyou Mar 14 '16 at 12:00
1 Answers
8
[I
is the output of getClass().getName ()
when executed on an int[]
. On the other hand, for Integer[]
, you'll get [Ljava.lang.Integer;
when calling getClass().getName ()
.
int[]
arrays are not autoboxed to Integer[]
.
[I@138a55
is not the hash code of the array, only the 138a55
part is the hex representation of the hash code of the array.
int
arrays don't override the default implementation of Object
's hashCode()
.

Eran
- 387,369
- 54
- 702
- 768
-
Note: the hashCode of an array is a code for the object not a hashCode of the contents of the array. – Peter Lawrey Mar 14 '16 at 11:34
-
wait.. If where is implementation of getClass().getName(); I don't see any calls to this method.. Is it internal implementation of JVM? – AskQ Mar 14 '16 at 11:49
-
1@AskQ The implementation of `Object`'s `toString()` is `return getClass().getName() + "@" + Integer.toHexString(hashCode());`. The implementation of `getName()` is in the `Class` class. `getClass` is a native method of the `Object` class, so we can't see its implementation. – Eran Mar 14 '16 at 11:52
-
if new int[] is not autoboxed to new Integer[] then toString() of Object should not be get called.. I don't understand how Object o=new int[]; woks as Object is not super class of int[] – AskQ Mar 14 '16 at 12:00
-
@AskQ An array is a sub-class of Object, regardless of whether the element type is primitive or not. Therefore `Object`'s `toString` is called. Object is a super class of int[]. – Eran Mar 14 '16 at 12:01
-
Heres what I figured out from comments.. thanks Eran, Peter..Step 1: Object o=new int[];
then step 2: o.toString() gets called which prints combination of getClass().getName () and the hex representation of the hash code of the array. – AskQ Mar 14 '16 at 12:20 -
also here new int[] is not autoboxed to int Integer[].. which I though before this question. – AskQ Mar 14 '16 at 12:22