Why does printing a Java array show a memory location [duplicate]
int[] answer= new int[map.size()];
HashMap<String, Integer> map = new HashMap<String, Integer>();
for (int j=0; j<answer.length;j++){
int x=map.get(keys.get(j));
answer[j]=x;
}
return answer
When I print x
using System.out.println(x)
in the loop, I get values of 1, 2, 3
but when I return the answer and print it, I get [I@9826ac5
. Any idea why?
Solution 1:
I[
is kind of the "class type" for an array of integer. Printing out this array itself will print the class type @
then a short hex string because that's the hash code of the array. It's the same as something you've probably seen like Object@0b1ac20
. This is implemented as the default toString()
for Object
.
Maybe you want to return a specific element of the array or print the whole array using a for loop?
Solution 2:
Long story short, you can't easily print an array in java. Do this:
System.out.println( Arrays.toString(answer) );
Solution 3:
because that is how array's toString()
method is implemented