Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does printing a Java array show a memory location [duplicate]

Tags:

java

arrays

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?

like image 616
dannyfrenton Avatar asked Feb 10 '13 05:02

dannyfrenton


People also ask

Are arrays stored contiguously in memory in Java?

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements.

How do you print an array in Java?

We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.


3 Answers

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?

like image 122
Dave Avatar answered Nov 03 '22 00:11

Dave


Long story short, you can't easily print an array in java. Do this:

System.out.println( Arrays.toString(answer) );
like image 45
redsaz Avatar answered Nov 03 '22 00:11

redsaz


because that is how array's toString() method is implemented

like image 25
jmj Avatar answered Nov 03 '22 00:11

jmj